There are many ways we can use JavaScript to check if a string contains numbers. We will go over two simple methods below to do this.
The first uses the JavaScript test() method and a regex expression.
/d/.test(someString);
The regex expression /d/
will check for any number from 0-9. The test() method will check the string you pass as a parameter to see if a number is contained in the string due to the regex expression. If it does find it, it returns true. Otherwise, it returns false.
We can wrap this code in a function to make it easy to reuse.
function stringContainsNumber(str){
return /d/.test(str);
};
Now let’s test this function with a couple of examples:
function stringContainsNumber(str){
return /d/.test(str);
};
var string1 = "This is a string with no numbers";
var string2 = "This is a string with numbers 1234567890";
var string3 = "This is a string a number 1";
var string4 = "123456";
var string5 = 12;
console.log(stringContainsNumber(string1));
console.log(stringContainsNumber(string2));
console.log(stringContainsNumber(string3));
console.log(stringContainsNumber(string4));
console.log(stringContainsNumber(string5));
#Output
false
true
true
true
true
Using JavaScript match() Method to Check if String Contains Numbers
We can also use the match() method to check if a string contains numbers along with a regex expression as we did with the test method.
someString.match(/d/);
The match() method will search the string, someString, for whatever you pass in as the parameter, which in this case is our regex expression for a number. The match() method will return an array with all of the matches, otherwise if a match is not found, it will return null.
Let’s put this code in a function as we did with the test() method.
function stringContainsNumber(str){
if( str.match(/d/) != null ){
return true;
} else {
return false;
}
};
And finally, let’s test this function as we did with our first function.
Now let’s test this function with a couple of examples:
function stringContainsNumber(str){
if( str.match(/d/) != null ){
return true;
} else {
return false;
}
};
var string1 = "This is a string with no numbers";
var string2 = "This is a string with numbers 1234567890";
var string3 = "This is a string a number 1";
var string4 = "123456";
console.log(stringContainsNumber(string1));
console.log(stringContainsNumber(string2));
console.log(stringContainsNumber(string3));
console.log(stringContainsNumber(string4));
#Output
false
true
true
true
Hopefully this article has been useful for you to learn how to use JavaScript to check if a string contains numbers.