
Using Regex to Replace Numbers in a 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 is still only doing single‑digit matches, however; the number 12,345 is being treated as five individual numbers in the replace() method.
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.
However, you could also delve further into number‑matching and use the \d character class. This matches any numeral and is the same as the [0‑9] format we've discussed above.
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.
Therefore, 1 would become 'one', but ‑ and this is where things prove a touch trickier ‑ it also needs to match and manage larger numbers. So 97 would become 'ninety‑seven', and ‑ an extreme example ‑ 78456327 would become 'seventy‑eight million four hundred fifty‑six thousand three hundred twenty‑seven'.
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'});It's worth mentioning that there are plenty of additional arguments available here, but for the sake of simplicity we'll just focus on the first (match) in this instance as it suits our needs.
Converting Matches into Numbers
For the final piece of the puzzle, we fall back on a package that I'm very fond of and have used a lot: number‑to‑words by Martin Eneqvist. This is a small, performant package that will ‑ as the name suggests ‑ take an integer, and convert it to a word. It has a raft of other features (like converting numbers to ordinals), but we just need the toWords() function here.
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().
Categories:
Related Articles

Intercepting Clipboard Events with JavaScript. 
Understanding JavaScript's sort() Method. Understanding JavaScript's
sort()Method
Default Parameters in JavaScript: A Guide. Default Parameters in JavaScript: A Guide

Improve Page Performance with content‑visibility. Improve Page Performance with
content‑visibility
Dynamic Routes in Next.js. Dynamic Routes in Next.js

Solving the LeetCode 'Binary Tree Zigzag Level Order Traversal' Problem. Solving the LeetCode 'Binary Tree Zigzag Level Order Traversal' Problem

The Differences Between Lead and Senior Roles in Front‑End Development. The Differences Between Lead and Senior Roles in Front‑End Development

Simplify Asynchronous JavaScript with async/await. Simplify Asynchronous JavaScript with
async/await
Asynchronous Module Definition (AMD) in JavaScript. Asynchronous Module Definition (AMD) in JavaScript

!Important in CSS. !importantin CSS
Enhancing Web Typography with text‑wrap: balance. Enhancing Web Typography with
text‑wrap: balance
Check If a String Contains Only Whitespace with JavaScript. Check If a String Contains Only Whitespace with JavaScript