Count the Number of Digits in a String in JavaScript

avatar

Borislav Hadzhiev

Tue Oct 26 20212 min read

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.

index.js
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.

index.js
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 #

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