Wed Oct 20 2021·2 min read
Photo by Nick Scheerbart
To remove all non-alphanumeric characters from a string, call the
method, passing it a regular expression that matches all non-alphanumeric
characters as the first parameter and an empty string as the second. The
replace method returns a new string with all matches replaced.
const str = 'A!@#b$%^c&*('; const replaced = str.replace(/[^a-z0-9]/gi, ''); console.log(replaced); // 👉️ Abc
We passed the following parameters to the String.replace method:
The forward slashes
/ / mark the beginning and end of the regular expression.
The square brackets
 are called a character class.
^ symbol means "not the following". In our case this means not any
letters in the range of
a-z and numbers in the range of
g(global) flag because we want to match all occurrences of non-alphanumeric characters and not just the first occurrence.
i flag makes our match case insensitive - we match all uppercase and
If you ever need help reading a regular expression, check this regex cheatsheet out. It's definitely the best one out there.
If your use case requires you to also preserve spaces, hyphens or other
characters, add them between the square brackets
const str = 'A!@# b$% ^c&-*('; const replaced = str.replace(/[^a-z0-9 -]/gi, ''); console.log(replaced); // 👉️ A b c-
The code snippet preserves, all alphanumeric characters, spaces and dashes. You
could adjust the regex to your needs, by adding or removing characters between
the square brackets