Remove Special Characters from a String in JavaScript

avatar

Borislav Hadzhiev

Thu Oct 07 20212 min read

Remove Special Characters from a String #

To remove all special characters from a string, call the replace() method, passing it a regex that matches all special characters and a replacement of an empty string. The replace method returns a new string with the matches replaced.

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 one.

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, you can 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 a bit, 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 then 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 it returns a new string with the matches replaced.

Join my newsletter

I'll send you 1 email a week with links to all of the articles I've written that week

Buy Me A Coffee