Remove all non-alphanumeric Characters from String in JS

avatar

Borislav Hadzhiev

Last updated: Jul 25, 2022

banner

Photo from Unsplash

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.

index.js
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 that we want to match in the string.
  2. the replacement for each match. For our purposes, 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 not any numbers in the range of 0-9.

We used 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 by targeting all uppercase and lowercase characters.

If you ever need help reading a regular expression, check out this regex cheatsheet by MDN.

If your use case requires you to also preserve spaces, hyphens or other characters, add them between the square brackets [].

index.js
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 hyphens. 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 #

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.