Check if String contains only Digits in JavaScript

avatar

Borislav Hadzhiev

Last updated: Jul 25, 2022

banner

Photo from Unsplash

Check if String contains only Digits #

Use the test() method to check if a string contains only digits, e.g. /^[0-9]+$/.test(str). 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 beginning and end of the regular expression.

The caret ^ matches the beginning of the input, and the dollar sign $ matches 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.

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 between 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 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 readable and intuitive.

Further Reading #

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.