在RegEx中修复JSLint错误的擒纵机构警告 [英] Fix JSLint bad escapement warning in RegEx
问题描述
我在第三方jQuery控件中有以下代码,名为 jquery.facebox.js , JSLint 不喜欢。这是RegEx中的一个错误的擒纵错误。
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.
正则表达式对于我来说就像是Romulan,所以我看不到如何解决错误(这是与期间字符在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');
推荐答案
添加第二个 \
之后'\
。这是一个字符串问题,而不是正则表达式问题: - )
Add a second \
after '\
. This is a string problem, not a regex problem :-)
要在一个字符串中有一个 \
Javascript(和许多其他语言)你需要逃脱它,因为它用于转义序列(如 \\\
)。所以要有一个
\
,你必须把 \\
。
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 \\.
要更清楚:你希望你的字符串是字面上 code> \。(某些东西。为了让你需要通过放一个来逃避
(否则你的字符串将是 \
\ 。(
,因为 \
会逃脱,所以它不会做任何事情)如果你好奇,正则表达式中的
。
意味着任何字符,但是如果你想搜索一个。
(一个点),你必须逃脱它,并猜测你使用什么? \
: - )
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 \
:-)
如果有一天你必须在C#中编程,在C#中,你可以使用 @something
。@ disable转义字符串中的扩展,所以 @\
是一个 \
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 \
这篇关于在RegEx中修复JSLint错误的擒纵机构警告的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!