为什么JSLint在以下
JavaScript行上返回“错误的擒纵”?
param = param.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
从JSLint文档中,我认为这是正确的,因为正则表达式文字前面有一个括号:@H_404_5@
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.@H_404_5@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.@H_404_5@
解决方法
这不是正式的表达,它是抱怨的.您正在转义不需要转义的替换字符串中的字符.
[和]字符在普通字符串中没有特殊的含义,你不必逃避他们:@H_404_5@
param = param.replace(/[\[]/,"\\[").replace(/[\]]/,"\\]");
注意:正如Anon指出的,您不需要为单个字符使用字符集:@H_404_5@
param = param.replace(/\[/,"\\[").replace(/\]/,"\\]");
您也可以在单个正则表达式中匹配两个字符,捕获匹配和替换中使用的字符.如果要替换第一次出现,则要使用全局选项:@H_404_5@
param = param.replace(/(\[|\])/g,"\\$1");