views:

607

answers:

1

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.

+4  A: 

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");
Guffa
Thx Guffa. I was about to update as after playingn around with it a bit more I figured out that I had an extra escape in there. My regex skills are terrible, this is part of a 'querystring' function I found on some website to retrieve parameters from the URL so I hadn't questionned it much as it was working. I see your one line version is much better though, thx!
SBUJOLD