Check if String contains only Digits in JavaScript

avatar

Borislav Hadzhiev

Thu Oct 21 20212 min read

banner

Photo by Kalen Emsley

Check if String contains only Digits #

To check if a string contains only digits, use the test() method with the following regular expression /^[0-9]+$/. The test method will return true if the string contains only digits and false otherwise.

index.js
function onlyNumbers(str) { return /^[0-9]+$/.test(str); } console.log(onlyNumbers('1234')); // ๐Ÿ‘‰๏ธ true console.log(onlyNumbers('123hello123')); // ๐Ÿ‘‰๏ธ false console.log(onlyNumbers('123.5')); // ๐Ÿ‘‰๏ธ false
If you need to match decimal or comma separated numbers, scroll down to the next code snippet.

We used the RegExp.test method to check if a string contains only digits.

The method returns true if the regular expression is matched in the string and false otherwise.

The forward slashes / / mark the start and end of the regular expression.

The caret ^ matches the beginning of the input and the dollar sign $ - the end of the input.

The part between the square brackets [] is called a character class and matches a range of digits from 0 to 9.

The plus + matches the preceding item (the 0-9 range) 1 or more times.

If you ever need help reading a regular expression, bookmark this regex cheatsheet from MDN. It's by far the best one out there.

If you need to also match decimal or comma separated numbers, add the character you'd like to match between the square brackets [].

index.js
function onlyNumbers(str) { return /^[0-9.,]+$/.test(str); } console.log(onlyNumbers('1234')); // ๐Ÿ‘‰๏ธ true console.log(onlyNumbers('123hello123')); // ๐Ÿ‘‰๏ธ false console.log(onlyNumbers('123.5')); // ๐Ÿ‘‰๏ธ true console.log(onlyNumbers('123,5')); // ๐Ÿ‘‰๏ธ true

We added a dot and a comma in the square brackets [] to also match these characters, if your use case requires other characters, simply add them between the square brackets.

Note that the regular expression of specifying a 0-9 range can also be written using the \d (digit) special character.

index.js
function onlyNumbers(str) { return /^\d+$/.test(str); } console.log(onlyNumbers('1234')); // ๐Ÿ‘‰๏ธ true console.log(onlyNumbers('123hello123')); // ๐Ÿ‘‰๏ธ false

The \d special character is equivalent to matching any digit using [0-9], but I find the range to be more intuitive and readable for developers who are not very familiar with regular expressions.

Further Reading #

Join my newsletter

I'll send you 1 email a week with links to all of the articles I've written that week

Buy Me A Coffee