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:
str
is a variable holding our initial string, “abc123def456”.\d
is a special symbol in RegEx that matches any digit (0-9).- The
+
symbol means “one or more” of the previous element. So\d+
means “one or more digits”. - 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. 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.- 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.