修复 RegEx 中的 JSLint 擒纵机构不良警告

发布于 2024-12-09 09:23:50 字数 340 浏览 2 评论 0原文

我在名为 jquery.facebox.js 的第三方 jQuery 控件中有以下代码,JSLint 不喜欢它。这是正则表达式中的一个严重的擒纵错误。

正则表达式对我来说就像 Romulan,所以我不知道如何修复错误(与正则表达式中的句点字符有关):

var imageTypes = $.facebox.settings.imageTypes.join('|');
$.facebox.settings.imageTypesRegexp = new RegExp('\.(' + imageTypes + ')$', 'i');

I have the following code in a 3rd party jQuery control called jquery.facebox.js that JSLint doesn't like. It's a bad escapement error in a RegEx.

Regular expression are like Romulan to me, so I can't see how to fix the error (which is with the period character in the RegEx):

var imageTypes = $.facebox.settings.imageTypes.join('|');
$.facebox.settings.imageTypesRegexp = new RegExp('\.(' + imageTypes + ')
, 'i');

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

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

发布评论

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

评论(2

歌枕肩 2024-12-16 09:23:50

'\ 之后添加第二个 \。这是一个字符串问题,而不是正则表达式问题:-)

要在 Javascript(和许多其他语言)中的字符串中包含 \,您需要对其进行转义,因为它用于转义序列(例如<代码>\n)。因此,要拥有 \,您必须输入 \\

在正则表达式中 \ 用于转义下一个字符,但这是另一种转义(与“字符串”转义无关)。所以它是 \\.

更清楚地说:您希望您的字符串“字面上” \.(something。为此,您需要转义 \ 通过放置另一个 \ (否则你的字符串将是 .( 因为 \ 会转义 . >,所以它不会做任何事情)。正则表达式中的 . 表示任何字符,但如果您想搜索 . (点),您必须对其进行转义,猜猜您使用什么? >\ :-)

如果有一天您必须使用 C# 进行编程,那么在 C# 中您可以使用 @"something" 中的 @disable escape “expansion” 来解决此问题。一个字符串。 @"\"\

Add a second \ after '\. This is a string problem, not a regex problem :-)

To have a \ in a string in Javascript (and many other languages) you need to escape it, because it is used for escape sequences (like \n). So to have a \ you have to put \\.

In regexes \ is used to escape the next character, but that is another escape (not connected to the "string" escape). So it's \\.

To be more clear: you want your string to be "literally" \.(something. To have that you need to escape the \ by putting another \ (otherwise your string would be .( because the \ would escape the ., so it wouldn't do anything). If you are curious, the . in regexes means any character, but if you want to search for a . (a dot), you have to escape it, and guess what you use? The \ :-)

If one day you'll have to program in C#, in C# you can solve this problem using the @"something". The @ disable escape "expansion" in a string. So @"\" is a \

对你而言 2024-12-16 09:23:50

如果您使用 / / 作为封装将模式定义为 Regex 对象,则不需要双重转义,因为它从来都不是字符串。

If you define your pattern as a Regex object using / / as enclosures, the double escaping isn't necessary as it is never a string.

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