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); |
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); |
false

… [Trackback]
[…] Read More to that Topic: geeksforgeeks.org/how-to-check-if-string-contains-only-digits-in-javascript-2/ […]