【发布时间】:2016-03-01 15:30:22
【问题描述】:
当您在带有String.prototype.search() 的搜索短语中使用方括号时,似乎会发生一些奇怪的事情:
var text = 'the needle in a [haystick]';
var result1 = text.search('[the] needle'); // 2
var result2 = text.search('[the]needle'); // -1
var result3 = text.search('[haystick]'); // 0
var result4 = text.search('\\[haystick\\]'); // 16
var result5 = text.search('['); // SyntaxError: Unterminated character class .
如果我用\\ 转义括号,它似乎可以正常工作。但是为什么呢?
【问题讨论】:
-
[the]是 RegEx 中的字符类。"\\[the\\]"将其解析为/\[the\]/转义方括号。
标签: javascript regex escaping