Fix JSLint bad escapement warning in RegEx

后端 未结 2 1953
陌清茗
陌清茗 2021-01-15 06:30

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 i

相关标签:
2条回答
  • 2021-01-15 06:54

    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 \

    0 讨论(0)
  • 2021-01-15 06:56

    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 讨论(0)
提交回复
热议问题