Fix JSLint bad escapement warning in RegEx

元气小坏坏 提交于 2019-12-01 10:00:25

问题


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');

回答1:


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 \




回答2:


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



来源:https://stackoverflow.com/questions/7735749/fix-jslint-bad-escapement-warning-in-regex

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!