使用 RegExp 删除所有特殊字符 [英] Remove all special characters with RegExp

查看:53
本文介绍了使用 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(/[^ws]/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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆