To check if a string contains only numeric digits in JavaScript, you can use regular expressions or iterate through each character and check if it is a digit.
In this example,
test
method of the regular expression object with the string to check if the string matches the pattern.matchDigits
will be true
, otherwise false
.let str1 = "12345";
let matchDigits = /^[0-9]+$/.test(str1);
console.log("String contains only numeric digits: " + matchDigits);
String contains only numeric digits: true
In this example,
containsOnlyNumericDigits
that takes a string as input.every
array method to iterate through each character and check if it is a digit.allDigits
will be true
, otherwise false
.function containsOnlyNumericDigits(str) {
return [...str].every(char => !isNaN(parseInt(char)));
}
let str2 = "12345";
let allDigits = containsOnlyNumericDigits(str2);
console.log("String contains only numeric digits: " + allDigits);
String contains only numeric digits: true
In this tutorial, we learned How to Check if String contains only Numeric Digits in JavaScript language with well detailed examples.