开发者

Fix JSLint bad escapement warning in RegEx

开发者 https://www.devze.com 2023-04-12 04:40 出处:网络
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.

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 i开发者_如何转开发mageTypes = $.facebox.settings.imageTypes.join('|');
$.facebox.settings.imageTypesRegexp = new RegExp('\.(' + imageTypes + ')$', 'i');


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 \


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

0

精彩评论

暂无评论...
验证码 换一张
取 消