Timothy Ruhle Timothy Ruhle - 3 months ago 12
Javascript Question

javascript regexp remove all special characters

I would like one RegExp that will remove all special characters from a string. I am trying something like this but it doesn't work in IE7 (which is what the works intranet uses). Works in Firefox.

var specialChars = "!@#$^&%*()+=-[]\/{}|:<>?,.";
for (var i = 0; i < specialChars.length; i++) {
stringToReplace = stringToReplace .replace(new RegExp("\\" + specialChars[i], 'gi'), '');
}


I suck with RegExp so a detailed description of it would be helpful as well.

Answer
var desired = stringToReplace.replace(/[^\w\s]/gi, '')

As was mentioned in the comments it's easier to do this as a whitelist - replace the characters which aren't in your safelist.

The caret (^) character is the negation of the set [...], gi say global and case-insensitive (the latter is a bit redundant but I wanted to mention it) and the safelist in this example is digits, word characters, underscores (\w) and whitespace (\s).

Comments