Remove special Characters from a String in JavaScript

avatar

Borislav Hadzhiev

Last updated: Jul 25, 2022

banner

Photo from Unsplash

Remove Special Characters from a String #

Use the replace() method to remove all special characters from a string, e.g. str.replace(/[^a-zA-Z0-9 ]/g, '');. The replace method will return a new string that doesn't contain any special characters.

index.js
const str = 'hello 123 !@#$%^WORLD?.'; const noSpecialCharacters = str.replace(/[^a-zA-Z0-9 ]/g, ''); console.log(noSpecialCharacters); // 👉️ 'hello 123 WORLD'

The first parameter we passed to the String.replace method is a regular expression.

We used the g (global) flag to match all occurrences of the regex in the string and not just the first occurrence.

The square brackets [] part denotes a character class and the caret ^ symbol means "not the following characters".

After the ^ (not) symbol we specify:

  • ranges for lower (a-z) and upper case (A-Z) letters. This only applies to the Latin alphabet.
  • a range for digits from (0-9)
  • a space character
In its entirety, the regular expression matches all characters but lower and uppercase letters, digits and spaces.

If you need to exclude other characters from being matched, add them between the square brackets [] of the regular expression.

If you don't know the syntax for a specific character, check out the MDN regex syntax cheatsheet.

We could also shorten the regular expression by using the \w character.

index.js
const str = 'hello 123 !@#$%^WORLD?._'; const noSpecialCharacters = str.replace(/[^\w ]/g, ''); console.log(noSpecialCharacters); // 👉️ 'hello 123 WORLD_'

This is slightly different than our previous example because the \w character matches:

  • ranges for lower (a-z) and upper case (A-Z) letters. This only applies to the Latin alphabet.
  • a range for digits from (0-9)
  • underscores

A very convenient way to check what a specific character matches is to look at the MDN cheatsheet.

If you need to exclude other characters from being removed, add them between the square brackets of the regex.

However, note that the caret ^ symbol has to be the first character in the square brackets to mean "not the following characters".

If you pass the caret ^ later in the regex, it will get interpreted literally as the ^ symbol.

Note that the String.replace method does not change the original string. Instead, the method returns a new string with the matches replaced.

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.