为什么 JSLint 在以下 JavaScript 行中返回“Bad escapement”?
param = param.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
根据 JSLint 文档,我认为这没问题,因为正则表达式文字前面有一个括号:
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.
最佳答案
它提示的不是正则表达式。您正在转义替换字符串中根本不需要转义的字符。
[ 和 ] 字符在普通字符串中没有特殊含义,您不必对它们进行转义:
param = param.replace(/[\[]/,"\\[").replace(/[\]]/,"\\]");
注意:正如 Anon 指出的,您不需要为单个字符使用字符集:
param = param.replace(/\[/,"\\[").replace(/\]/,"\\]");
您还可以在单个正则表达式中匹配两个字符,捕获匹配的内容并在替换中使用。如果你想替换不止第一次出现,你想使用全局选项:
param = param.replace(/(\[|\])/g,"\\$1");
关于javascript - 为什么 JSLint 在这行代码中返回 'bad escapement'?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2338547/