Sunday, December 29, 2024
Google search engine
HomeLanguagesJavascriptHow to check if string contains only digits in JavaScript ?

How to check if string contains only digits in JavaScript ?

Given a string and the task is to check whether the string contains only digits or not.

JavaScript test() Method to Check a String Contains Only Digits

This method tests for a pattern in a string. This method returns true if the match is found, otherwise, it returns false.

Syntax:

RegExpObject.test(str)

Parameters: This function accepts single parameter str which is required. It specifies the string which to be searched.

Example 1: This example checks for the non-digit string by using RegExp.

Javascript




function checkStrDigit(str) {
    console.log(/^\d+$/.test(str));
}  
 
const str = "4323424242";
checkStrDigit(str);


Output

true

Example 2: This example checks for the non-digits string by using RegExp.

Javascript




function checkStrDigit(str) {
    console.log(!/\D/.test(str));
}
 
const str = "+4323424242";
checkStrDigit(str);


Output

false

Whether you’re preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, neveropen Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we’ve already empowered, and we’re here to do the same for you. Don’t miss out – check it out now!

RELATED ARTICLES

Most Popular

Recent Comments