jshint 正则表达式中的未转义字符
我正在尝试使用 jshint 清理一些 Javascript 代码。在正在使用的第三方脚本中,jshint 抱怨这一行中的未转义的 javascript:
var cleanString = deaccentedString.replace(/([|()[{.+*?^$\\])/g,"\\$1");
我也想了解这个正则表达式的作用,但我没有看到它。谁能告诉我这是做什么的以及如何以干净的方式编写它?
感谢您的任何提示。
I am trying to cleanup some Javascript code using jshint. In a third-party script that is being used, jshint complains about unescaped javascript in this line:
var cleanString = deaccentedString.replace(/([|()[{.+*?^$\\])/g,"\\$1");
I'd also like to understand what this regular expression does, but I don't see it. Can anyone tell me what this is for and how to write it in a cleaned up way?
Thank your for any hints.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
它匹配以下任何字符:
|()[{.+*?^$\
并将其替换为其转义的对应字符(反斜杠加该字符)。虽然在许多正则表达式方言中在字符类中包含未转义的
[
是合法的,但它可能会在其他语言中触发错误,因此请尝试以下操作:(也可以删除不必要的捕获组。)
It matches any of the following characters:
|()[{.+*?^$\
and replaces it with its escaped counterpart (backslash plus that character).While it is legal in many regex dialects to include an unescaped
[
inside a character class, it can trigger an error in others, so try this:(the unnecessary capturing group could be dropped, too.)
正则表达式选择“特殊”字符并在前面填充反斜杠。我的猜测是它不喜欢字符类中赤裸裸的“[”,但这只是一个猜测。您可以尝试:
您的另一个选择是不用担心 jshint 所说的;毕竟,它只是一个咨询工具,如果代码实际上在所有浏览器中都能正常工作,那么这个建议显然很糟糕:-)
The regex is selecting "special" characters and stuffing a backslash in front. My guess is that it doesn't like the naked "[" in the character class, but that's just a guess. You might try:
Another option you have is to just not worry about what jshint says; it's just an advisory tool, after all, and if the code actually works properly in all browsers, well, the advice is clearly bad :-)