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
