jshint 正则表达式中的未转义字符

发布于 2024-11-14 11:38:23 字数 259 浏览 0 评论 0原文

我正在尝试使用 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

旧伤慢歌 2024-11-21 11:38:23

它匹配以下任何字符:|()[{.+*?^$\ 并将其替换为其转义的对应字符(反斜杠加该字符)。

虽然在许多正则表达式方言中在字符类中包含未转义的 [ 是合法的,但它可能会在其他语言中触发错误,因此请尝试以下操作:(

var cleanString = deaccentedString.replace(/[|()\[{.+*?^$\\]/g,"\\$0");

也可以删除不必要的捕获组。)

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:

var cleanString = deaccentedString.replace(/[|()\[{.+*?^$\\]/g,"\\$0");

(the unnecessary capturing group could be dropped, too.)

笑脸一如从前 2024-11-21 11:38:23

正则表达式选择“特殊”字符并在前面填充反斜杠。我的猜测是它不喜欢字符类中赤裸裸的“[”,但这只是一个猜测。您可以尝试:

var cleanString = deaccentedString.replace(/([|()\[{.+*?^$\\])/g,"\\$1");

您的另一个选择是不用担心 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:

var cleanString = deaccentedString.replace(/([|()\[{.+*?^$\\])/g,"\\$1");

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 :-)

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文