/* Code-Comments */

RegEx In Javascript Strings: Remove numeric or alphabetic characters

September 04, 2019

Built into Javascript’s String primitive are Regex methods such as .match and .replace.1

We can use the latter to sanitize inputs. A simply way to clean a phone number, for example is phoneNumber.replace(/[^0-9]/g, "").

As you can see in this RegexPal2, the non-numbers are highlighted:

To use this in a function, it’s as simple as:

const phone = '+1 (123) 456-9800'
console.log(phone.replace(/[^0-9]/g, '')) // 11234569800

To replace alphabetic characters, we would modify the pattern. For example /[^A-z]/g would be all upper and lower case characters.

Footnotes:


Stephen Weiss

Thanks for reading! My name's Stephen Weiss. I live in Chicago with my wife, Kate, and dog, Finn.
Click here to see the archives of my weeks in review and sign up yourself!