Using Regex to Replace Numbers in a String

In Brief
Use /[0-9]+/g or /\d+/g with replace() to match consecutive ASCII digits. The callback can turn each match into replacement text. This is digit‑run replacement, not a parser for signed, decimal or grouped numbers; decide which numeric text should change before applying it to a whole string.
I've talked about using the JavaScript replace() method alongside regular expressions (regex) before, but I came across another interesting example in a recent project that I felt deserved a little documentation of its own.
Essentially: how do you detect instances of numbers (specifically numerical digits) in a string?
The Regex
We can use our regex function to detect a group between zero and nine like so: /[0-9]/. However, this will only match the first instance, and only match a single digit:
const string = '12345';
console.log(string.replace(/[0-9]/, 'number '));
//=> 'number 2345'As we've discussed previously, regex will allow us to match every instance by including the global modifier: /g, which would then look like this:
const string = '12345';
console.log(string.replace(/[0-9]/g, 'number '));
//=> 'number number number number number 'This still makes single‑digit matches: the five digits in 12345 are replaced separately.
We can combine everything above with the + quantifier, which essentially then means "match any digit one or more times":
const string = '12345';
console.log(string.replace(/[0-9]+/g, 'number '));
//=> 'number 'The \d character class
I have always found that when it comes to regex, readability for the next developer is probably just as important ‑ if not slightly more so ‑ than performance. It's no good writing code that nobody understands, so for the most part I tend to stick with the [0-9] format as it makes logical sense at a glance.
JavaScript's \d character class also matches ASCII digits from 0 to 9, so it is equivalent to [0-9] here. It does not mean every numeral in every writing system. Adding + groups adjacent digits, but signs, decimal points and thousands separators remain outside the match.
Thus, this is the same outcome as the previous example.
const string = '12345';
console.log(string.replace(/\d+/g, 'number '));
//=> 'number 'It's up to you to decide which makes more sense for you, your project, and your teammates.
Replacing Numbers with Words
In my specific instance, I needed to match integers (numerals) within a string and replace these instead with the word version.
For example, 1 becomes "one" and 97 becomes "ninety-seven". With the package used below, 78456327 becomes "seventy-eight million, four hundred fifty-six thousand, three hundred twenty-seven". That is the package's wording and punctuation, rather than a choice about British number style.
The replace() method with a function
Whilst replace() is often used for fairly rudimentary string replacements, you can also use a function in the replacement parameter where the first argument is the match.
const string = '12345';
string.replace(/\d+/g, match => {
console.log('match is: ', match);
//=> 'match is: 12345'
return match;
});The callback receives other arguments too, but the first is enough here. It must return the replacement text. In this logging example, returning match leaves the matched text unchanged.
Converting Matches into Numbers
For the conversion, I use number-to-words by Martin Eneqvist. Its toWords() function converts integers into words. Version 1.2.4 accepts integer strings but rejects values outside JavaScript's safe‑integer range. For the unsigned digit runs matched here, keep values from 0 through 9007199254740991. Do not apply this blindly to phone numbers, reference codes or other identifiers whose digits and leading zeros need to stay intact.
It's available via your favourite package manager, and can then be imported where you need it:
import { toWords } from 'number-to-words';Stitching It All Together
So, to replace sets of numbers within a string, with their text equivalents, we just need to stitch everything together:
- Use
replace()method; - Use the
/gflag and+quantifier to match sets of numbers; - Pass these
matchesintotoWordsfromnumber-to-words.
Something a little like this:
const numbersToWords = string =>
string.replace(/\d+/g, match => toWords(match));Which results in:
console.log(
numbersToWords(
'Typically, a space shuttle crew is made up of 5 to 7 crewmembers'
)
);
//=> 'Typically, a space shuttle crew is made up of five to seven crewmembers'
console.log(
numbersToWords(
'During the 30 years that NASA flew the space shuttle, they completed 135 missions'
)
);
//=> 'During the thirty years that NASA flew the space shuttle, they completed one hundred thirty-five missions'
console.log(
numbersToWords(
'The final orbital speed of the space shuttle was approximately 28000 kmh (or 17500 mph)'
)
);
//=> 'The final orbital speed of the space shuttle was approximately twenty-eight thousand kmh (or seventeen thousand, five hundred mph)'And that's it! For more information on Regular Expressions, Mozilla has a great cheat sheet here, and in‑depth documentation here for String.prototype.replace().