Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fix JSLint bad escapement warning in 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 imageTypes = $.facebox.settings.imageTypes.join('|');
$.facebox.settings.imageTypesRegexp = new RegExp('\.(' + imageTypes + ')$', 'i');
like image 898
Armchair Bronco Avatar asked Dec 05 '25 10:12

Armchair Bronco


1 Answers

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 \

like image 155
xanatos Avatar answered Dec 08 '25 00:12

xanatos



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!