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.
str.replace(/\s|[0-9_]|\W|[#$%^&*()]/g, "")
I did sth like this. But there is some people who did it much easier likestr.replace(/\W_/g,"");
use regex
^[^/\\()~!@#$%^&*{«»„““”‘’|\n\t….,;`^"<>'}+:?®©]*$
The first solution does not work for any UTF-8 alphabet. (It will cut text such as Їжак). I have managed to create a function which does not use RegExp and use good UTF-8 support in the JavaScript engine. The idea is simple if a symbol is equal in uppercase and lowercase it is a special character. The only exception is made for whitespace.
Update: Please note, that this solution works only for languages where there are small and capital letters. In languages like Chinese, this won't work.
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
).why dont you do something like:
to check if your input contain any special char
Plain Javascript regex does not handle Unicode letters.
Do not use
[^\w\s]
, this will remove letters with accents (like àèéìòù), not to mention to Cyrillic or Chinese, letters coming from such languages will be completed removed.You really don't want remove these letters together with all the special characters. You have two chances:
for example:
[^èéòàùì\w\s]
.\p{...}
syntax.