Tuesday, July 28, 2026
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

Dominic
32520 POSTS0 COMMENTS
Milvus
131 POSTS0 COMMENTS
Nango Kala
6903 POSTS0 COMMENTS
Nicole Veronica
12017 POSTS0 COMMENTS
Nokonwaba Nkukhwana
12115 POSTS0 COMMENTS
Shaida Kate Naidoo
7023 POSTS0 COMMENTS
Ted Musemwa
7265 POSTS0 COMMENTS
Thapelo Manthata
6980 POSTS0 COMMENTS
Umr Jansen
6972 POSTS0 COMMENTS