Borislav Hadzhiev
Thu Oct 07 2021·2 min read
Photo by Matteo Di Iorio
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.
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:
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.
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:
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.
String.replace
method does not change the original string, instead it returns a new string with the matches replaced.