删除 JavaScript 中的无效字符
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12754256/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Removing invalid characters in JavaScript
提问by Chris
Can someone provide a regular expression to search and replace illegal characters found
有人可以提供正则表达式来搜索和替换发现的非法字符吗
Example, removing ?
例如,删除 ?
I am not sure how many types of 'illegal' characters exist but I think this will be a good start.
我不确定存在多少种“非法”字符,但我认为这将是一个好的开始。
Many thanks
非常感谢
edit - I have no control over the data, we're trying to create a catch for the potentially bad data we're receiving.
编辑 - 我无法控制数据,我们正在尝试为我们收到的潜在错误数据创建一个捕获。
回答by saml
回答by allyourcode
Instead of having a blacklist, you could use a whitelist. e.g. If you want to only accept letters, numbers, space, and a few punctuation characters, you could do
您可以使用白名单而不是黑名单。例如,如果您只想接受字母、数字、空格和一些标点符号,您可以这样做
myString.replace(/[^a-z0-9 ,.?!]/ig, '')
回答by Kapil Thakkar
Try this, it will work for all unexpected character like ? ? etc...
试试这个,它适用于所有意想不到的角色,比如?? 等等...
dataStr.replace(/[\u{0080}-\u{FFFF}]/gu,"");