使用RegExp删除所有特殊字符 [英] Remove all special characters with RegExp
问题描述
我想要一个将从字符串中删除所有特殊字符的RegExp。我正在尝试这样的东西,但它在IE7中不起作用,虽然它适用于Firefox。
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"), "");
}
RegExp的详细说明也会有所帮助。
A detailed description of the RegExp would be helpful as well.
推荐答案
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.
插入符号( ^
)字符是集合的否定[... ]
, gi
说全局和不区分大小写(后者有点多余,但我想提一下),本例中的安全列表是数字,单词字符,下划线( \w
)和空格( \s
)。
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
).
这篇关于使用RegExp删除所有特殊字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!