How to Remove all Characters Except Numbers in JavaScript


Borislav Hadzhiev

Fri Oct 08 20212 min read


Photo by Gus Ruballo

Remove all Characters Except Numbers in JavaScript #

To remove all characters except numbers in javascript, call the replace() method, passing it a regular expression that matches all non-number characters and replace them with an empty string. The replace method returns a new string with some or all of the matches replaced.

const str = 'hello 123 !@#$%^WORLD?456._'; const onlyNumbers = str.replace(/\D/g, ''); console.log(onlyNumbers); // ๐Ÿ‘‰๏ธ 123456

The first parameter we passed to the String.replace method is a regular expression.

We used the g (global) flag to denote that the regular expression should match all occurrences in the string and not just the first one.

The \D character matches all non-digit characters.

For a complete regex cheatsheet, check out this MDN table.

The second parameter we pass to the replace method is the replacement for any matches, in our case an empty string.

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

In our code we replace all non-digit characters with an empty string, essentially remove all non-digit characters.

This wouldn't work if you have floats in your string, because the dots . would also get stripped.

If you are trying to preserve a float number by keeping dots in the final result, things can go wrong if the string contains multiple dots or a dot at the wrong place.

If you want to leave dots in the final string to try to preserve float numbers, use the following regex.

const str = 'hello 123 !@#$%^WORLD?.456_'; const onlyNumbers = str.replace(/[^\d.]/g, ''); console.log(onlyNumbers); // ๐Ÿ‘‰๏ธ 123.456

The caret ^ symbol in the regex means "NOT the following".

In our case we match all non-digits or dots.

The \d character matches all digits (0-9), however we have prefixed it with ^ (not), so in it's entirety the regex matches all non-digit characters or dots.

As previously mentioned things can go wrong if multiple dots exist in the string or a dot is at the wrong spot.

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