Last updated: Jul 25, 2022
Check out my new book
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.
g(global) flag to denote that the regular expression should match all occurrences in the string, and not just the first occurrence.
\D character matches all non-digit characters.
For a complete regex cheatsheet, check out this MDN table.
The second parameter we passed to the
replace method is the replacement for
each match, in our case an empty string.
For our purposes, we replace all non-digit characters with an empty string in order to remove non-digits from the string.
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".
We match all non-digits or dots in the example.
\dcharacter matches all digits in the range [0-9]. However, we prefixed it with a caret
^(not). So in it's entirety the regex matches all non-digit characters or dots.
As previously noted, things can go wrong if multiple dots exist in the string or a dot is at the wrong place.