Saturday, October 25, 2025
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
32361 POSTS0 COMMENTS
Milvus
88 POSTS0 COMMENTS
Nango Kala
6728 POSTS0 COMMENTS
Nicole Veronica
11892 POSTS0 COMMENTS
Nokonwaba Nkukhwana
11954 POSTS0 COMMENTS
Shaida Kate Naidoo
6852 POSTS0 COMMENTS
Ted Musemwa
7113 POSTS0 COMMENTS
Thapelo Manthata
6805 POSTS0 COMMENTS
Umr Jansen
6801 POSTS0 COMMENTS