Remove all Numbers from a String in JavaScript


Borislav Hadzhiev

Last updated: Oct 13, 2021


Photo from Unsplash

Remove all Numbers from a String #

To remove all numbers from a string, call the replace() method, passing it a regular expression that matches all numbers as the first parameter and an empty string as the second. The replace method will return a new string that doesn't contain any numbers.

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

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

  1. a regular expression we want to match in the string - in our case we want to match all numbers from 0 to 9
  2. a replacement string for each match - for our purposes an empty string, because we want to remove all numbers
By replacing each number with an empty string, we achieve our goal of removing all numbers from the string.

The brackets [] part of a regular expression is called a character class. In our character class we match all numbers in the range 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 replace method does not change the original string, it returns a new string with one or more matches replaced. Strings are immutable in JavaScript.

An equivalent regular expression, is to use the \d special character.

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

The \d special character matches any digit in the range of 0-9. It achieves the same goal as our previous regex, which used [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.