Remove all special characters from a string?

nick asked this question 8 months ago
nick on Feb 7 · Edited

How can I easily remove all the special characters from my JavaScript strings?

Things like question marks, periods, hashes, parenthesis, etc. need to be removed.

For instance, I'll commonly have any of these characters in a string:

"my string 123@!#%^$?";

That string would need to be converted into this:

"my string123"

Thanks for the help in advance!

5 suggested answers
moon_man41 on Mar 13
function removeSpecialCharacters(string) {
    return string
        .replace(/(?!\w|\s)./g, "")
        .replace(/\s+/g, " ")

A quick breakdown of each part:

  • .replace(/(?!\w|\s)./g, ""): replaces everything in the string besides alphanumeric characters and spaces.
  • .replace(/\s+/g, " "): finds any instance of two consecutive spaces and replaces it with one space.
  • .trim(): removes any white space at the beginning or end of the string.

To use the function, you can just pass in your string as the parameter:

0 replies
rusty1_rusty1 on Mar 13

If you want to remove all special characters from your string, use this regex:

string.replace(/[^a-z0-9,. ]/gi, "");

The pattern is [^a-z0-9,. ]. Which means it will match any characters besides spaces, letters, numbers, periods, or commas.

You can also use a regex that removes only specific characters:

string.replace(/[@!#%^$?]/g, "");

This will match and replace the following characters: @, !, #, %, ^, $, ?.

0 replies
coderguy on Mar 13
const newString = ogString.replace(/[`~!@#$%^&*()_|+\-=?;:'",.<>\{\}\[\]\\\/]/gi, "");

This regular expression allows you to specifically list which special characters you want removed. Notice that some characters are escaped using \.

This should work for removing the special characters from your strings.

0 replies
yaboy01 on Mar 13 · Edited

Another regular expression you can use:

let string = "my string 123@!#%^$?";

string = string.replace(/[^a-zA-Z0-9 ]/g, "");

// string = "my string 123"

The regular expression all characters besides letters and numbers.

0 replies
itsbambi on Mar 13

Try this regular expression and replace() method:

myString = myString.replace(/[^\w ]/g, "");

This will remove the special characters from your string.

0 replies