Fri Oct 08 2021·2 min read
Photo by Gus Ruballo
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.
\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.
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 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
^ symbol in the regex means "NOT the following".
In our case we match all non-digits or dots.
\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
As previously mentioned things can go wrong if multiple dots exist in the string or a dot is at the wrong spot.
I'll send you 1 email a week with links to all of the articles I've written that week