Why is it that JSLint returns a 'Bad escapement' on the following JavaScript line ?
param = pa开发者_如何转开发ram.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");
精彩评论