Replace all Numbers in a String using JavaScript

avatar

Borislav Hadzhiev

Last updated: Jul 25, 2022

banner

Photo from Unsplash

Replace all Numbers in a String #

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.

The replace method will return a new string with all matches replaced by the provided replacement.

index.js
const str = 'a1 b2 c3'; const replaced = str.replace(/[0-9]/g, '!'); console.log(replaced); // 👉️ a! b! c!

We passed the following parameters to the String.replace method:

  1. a regular expression we want to match in the string. For our purposes, all numbers from 0-9
  2. the replacement string for each match

The brackets [] are called a character class. The character class in the examples matches all numbers in the range 0 to 9.

We used 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.

The replace method doesn't change the original string, it returns a new string with one or more matches replaced. Strings are immutable in JavaScript.

The example uses an exclamation mark as the replacement, however you could use whatever replacement string suits your use case, e.g. an underscore.

index.js
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.

index.js
const str = 'a1 b2 c3'; const replaced = str.replace(/\d/g, '!'); console.log(replaced); // 👉️ a! b! c!

The \d special character matches any digit 0-9. It achieves the same result as [0-9].

Further Reading #

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.