Wed Oct 13 2021·2 min read
Photo by Cristy Zinn
To replace all numbers in a string, call the
replace() method, passing it a
regular expression that globally matches all numbers as the first parameter and
the replacement string as the second.
replace method will return a new string with all matches replaced by the
const str = 'a1 b2 c3'; const replaced = str.replace(/[0-9]/g, '!'); console.log(replaced); // 👉️ a! b! c!
We pass the following parameters to the String.replace method:
 part of a regular expression is called a character class. In
our character class we match all numbers in the range from 0-9.
We use the
g (global) flag, because we want to match all occurrences of a
number in the string and not just the first occurrence.
If you need help reading a regular expression, check out this regex cheatsheet from MDN. It's definitely the best one out there.
The example uses an exclamation mark as the replacement, however you could use whatever replacement string suits your use case, e.g. an underscore.
const str = 'a1 b2 c3'; const replaced = str.replace(/[0-9]/g, '_'); console.log(replaced); // 👉️ a_ b_ c_
An equivalent regular expression, is to use the
\d special character.
const str = 'a1 b2 c3'; const replaced = str.replace(/\d/g, '!'); console.log(replaced); // 👉️ a! b! c!
\d special character matches any digit 0-9. It achieves the same goal as
I'll send you 1 email a week with links to all of the articles I've written that week