Last updated: Jul 25, 2022
Photo from Unsplash
replace() method to remove all special characters from a string,
str.replace(/[^a-zA-Z0-9 ]/g, '');. The
replace method will return a
new string that doesn't contain any special characters.
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.
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".
^ (not) symbol we specify:
If you need to exclude other characters from being matched, add them between the
 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
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
A very convenient way to check what a specific character matches is to look at the MDN cheatsheet.
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
String.replacemethod does not change the original string. Instead, the method returns a new string with the matches replaced.