Count the Number of Digits in a String in JavaScript


Borislav Hadzhiev

Last updated: Oct 26, 2021


Photo from Unsplash

Count the Number of Digits in a String #

To count the number of digits in a string, use the replace() method to replace all non digit characters with an empty string and access the length property on the result. The replace method returns a new string with the matches replaced.

function getCountOfDigits(str) { return str.replace(/[^0-9]/g, '').length; } console.log(getCountOfDigits('12hello34')); // 👉️ 4 console.log(getCountOfDigits('hello')); // 👉️ 0 console.log(getCountOfDigits('hello12.5')); // 👉️ 3

We used the String.replace method to replace all non-digit characters in the string, so we can get the length of the string containing only digits.

The first parameter we passed to the replace method is a regular expression and the second a replacement for each match of the result expression in the string.

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

The part between the square brackets [] is called a character class.

The caret ^ symbol means "not the following", in other words we're matching anything but a range of digits from 0-9.

We used the g (global) flag because we want to match all occurrences of non-digit characters in the string and not just the first occurrence.

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

The second parameter we passed to the replace method is a replacement string for each match. Because we want to remove all non-digit characters, we provided an empty string.

The replace method does not change the contents of the original string, it returns a new string. Strings are immutable in JavaScript.

In its entirety, the regular expression replaces all non-digit characters with an empty string.

console.log('hello123'.replace(/[^0-9]/g, '')); // 👉️ 123

The last step is to access the length property on the new string, which gets us the number of digits in the original string.

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.