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