Why is it that JSLint returns a 'Bad escapement' on the following JavaScript line ?
param = param.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
From JSLint documentation I thought that this would be ok since the regex literal is preceeded by a parenthesis:
Regular expressions are written in a terse and cryptic notation. JSLint looks for problems that may cause portability problems. It also attempts to resolve visual ambiguities by recommending explicit escapement.
JavaScript's syntax for regular expression literals overloads the / character. To avoid ambiguity, JSLint expects that the character preceding a regular expression literal is a ( or = or : or , character.
It's not the regular expression that it's complaining about. You are escaping characters in the replacement strings that doesn't need escaping at all.
The [ and ] characters have no special meaning in an ordinary string, you don't have to escape them:
param = param.replace(/[\[]/,"\\[").replace(/[\]]/,"\\]");
Note: As Anon pointed out, you don't need to use a character set for a single character:
param = param.replace(/\[/,"\\[").replace(/\]/,"\\]");
You can also match both characters in a single regular expression, catch what you match and use in the replacement. If you want to replace more than the first occurance, you want to use the global option:
param = param.replace(/(\[|\])/g,"\\$1");
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With