Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove all special characters with RegExp

I would like a RegExp that will remove all special characters from a string. I am trying something like this but it doesn’t work in IE7, though it works in Firefox.

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

A detailed description of the RegExp would be helpful as well.

like image 498
Timothy Ruhle Avatar asked Dec 07 '10 08:12

Timothy Ruhle


People also ask

How do you stop special characters in regex?

Escape Sequences (\char): To match a character having special meaning in regex, you need to use a escape sequence prefix with a backslash ( \ ). E.g., \. matches "." ; regex \+ matches "+" ; and regex \( matches "(" .


Video Answer


1 Answers

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

like image 74
annakata Avatar answered Oct 05 '22 12:10

annakata