javascript 正则表达式中的 JSLint“不安全 ^”
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4109214/
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
JSLint "insecure ^" in regular expression
提问by Thomas R
JSLint reports Insecure '^'for the following line. Why is that? Or is it just going to complain any time I want to negate a character class?
JSLint 报告以下行的不安全“^”。这是为什么?或者它会在我想否定一个角色类的任何时候抱怨吗?
// remove all non alphanumeric, comma and dash characters
"!s-gd,&j5d-a#".replace(/[^\w,\-]/g, '');
采纳答案by Nick Craver
It only will do this if you have the option selected at the bottom:
如果您在底部选择了选项,它只会执行此操作:
Disallow insecure . and [^...] in /RegExp/
From the docs:
从文档:
true if . and [^...] should not be allowed in RegExp literals. These forms should not be used when validating in secure applications.
真如果。和 [^...] 不应该出现在 RegExp 文字中。在安全应用程序中进行验证时,不应使用这些表单。
So the answer your question, if you start a regex with ^and it's checked, yes it'll throw the error every time. The issue is with unicode characters, you're allowing pretty much anything in there and there's potential for security issues, or validation bypassing issues. Instead of disallowingsomething (which can be bypassed), allowonly what characters are valid.
所以回答你的问题,如果你开始一个正则表达式^并检查它,是的,它每次都会抛出错误。问题在于 unicode 字符,您几乎可以在其中使用任何内容,并且可能会出现安全问题或绕过验证的问题。而不是禁止某些东西(可以绕过),只允许哪些字符是有效的。
回答by David Morrow
regexp: true
regexp: true
in your lint options, will allow
在您的 lint 选项中,将允许
. and [^...] in /RegExp/
. and [^...] in /RegExp/
you can configure the rules you would like to use here
你可以在这里配置你想使用的规则
回答by dugokontov
Consider using \Winstead of /^\w/
考虑使用\W代替/^\w/
"!s-gd,&j5d-a#".replace(/\W/g, '');
For your particular case this would not work because you want to leave comma and dash characters, but I think it is worth mentioning.
对于您的特定情况,这不起作用,因为您想留下逗号和破折号字符,但我认为值得一提。

