How to Remove Numbers From a String With RegEx

This tutorial will teach you how to match and remove all the numbers in a string using RegEx.

Published Categorized as JavaScript

If you need to remove the numbers from a string in JavaScript, you can achieve this with RegEx.

RegEx, or a “regular expression,” is a sequence of characters that describes a pattern for matching in a string.

For instance, you might use a regular expression to search for all instances of the word “the” in a text document, or to find all email addresses in a web page, or—in the case of this tutorial—to find all numbers in a string so that you can remove them by replacing them with nothing.

Removing the Numbers From a String With RegEx

Here’s a JavaScript code snippet:

let str = "abc123def456";
let result = str.replace(/\d+/g, '');
console.log(result);  // abcdef

Let’s break this code snippet, and the regular expression that it contains, down:

  1. str is a variable holding our initial string, “abc123def456”.
  2. \d is a special symbol in RegEx that matches any digit (0-9).
  3. The + symbol means “one or more” of the previous element. So \d+ means “one or more digits”.
  4. The g at the end is a flag that tells the regular expression to apply the replacement globally in the string. Without it, only the first match would be replaced.
  5. replace is a JavaScript function that we use here to replace each matching part of the string (each digit, in this case) with something else. In this case, we’re replacing it with nothing (''), effectively removing the digits.
  6. The result is stored in the variable result, and then we log it to the console.

So, basically, this code snippet finds every digit in the string and then removes it.

The result is the original string, but without any numbers.

By Dim Nikov

Editor of Maker's Aid. Part programmer, part marketer. Making things on the web and helping others do the same since the 2000s. Yes, I had Friendster and Myspace.

Leave a comment

Your email address will not be published. Required fields are marked *