We can use JavaScript to check if a string contains only numbers. One of the simplest ways to do this is to use the JavaScript test() method and a regex expression.

/^d+$/.test(someString);

The regex expression d will check for any number from 0-9. The rest of the regex expression checks that every character in the string is equal to a number 0-9. Here is a useful resource on regex expressions if you want to learn more about them. The test() method will check the string you pass as a parameter to see if only numbers are contained in the string due to the regex expression. If it does find all numbers, it returns true. Otherwise, it returns false.

We can wrap this code in a function to make it easy to reuse.

function stringContainsOnlyNumbers(str){
  return /^d+$/.test(str);
};

Now let’s test this function with a couple of examples:

function stringContainsOnlyNumbers(str){
  return /^d+$/.test(str);
};

var string1 = "This is a string with numbers 1234567890";
var string2 = "123456";
var string3 = " 123456";
var string4 = 12;
var string5 = "$1000";
var string6 = "10.234";


console.log(stringContainsOnlyNumbers(string1));
console.log(stringContainsOnlyNumbers(string2));
console.log(stringContainsOnlyNumbers(string3));
console.log(stringContainsOnlyNumbers(string4));
console.log(stringContainsOnlyNumbers(string5));
console.log(stringContainsOnlyNumbers(string6));

#Output
false
true
false
true
false
false

Notice in our last example the string “10.234” returns false because “.” is not a number. If we wanted to include this as being a number, we could just add “.” to our regex expression.

function stringContainsOnlyNumbers(str){
  return /^d.+$/.test(str);
};

var string1 = "10.234";

console.log(stringContainsOnlyNumbers(string1));

#Output
true

Hopefully this article has been useful for you to learn how to use JavaScript to check if a string contains only numbers.

Categorized in:

JavaScript,

Last Update: March 11, 2024