Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does JSLint returns 'bad escapement' on this line of code?

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.

like image 514
SBUJOLD Avatar asked Feb 26 '10 00:02

SBUJOLD


1 Answers

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");
like image 150
Guffa Avatar answered Oct 19 '22 23:10

Guffa