Remove all non-alphanumeric Characters from String in JS


Borislav Hadzhiev

Wed Oct 20 20212 min read

Remove all non-alphanumeric Characters from String #

To remove all non-alphanumeric characters from a string, call the replace() 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
If you also want to preserve spaces, hyphens or other characters, scroll down to the next code snippet.

We passed the following parameters to the String.replace method:

  1. a regular expression we want to match in the string
  2. a replacement for each match. In our case - an empty string because we want to remove all non-alphanumeric characters.

The forward slashes / / mark the beginning and end of the regular expression.

The square brackets [] are called a character class.

The caret ^ 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 0-9.

We use the g (global) flag because we want to match all occurrences of non-alphanumeric characters and not just the first occurrence.

The i flag makes our match case insensitive - we match all uppercase and lowercase characters.

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 [].

The replace method does not change the contents of the original string, it returns a new string. Strings are immutable in JavaScript.

Further Reading #

Use the search field on my Home Page to filter through my more than 1,000 articles.