【问题标题】:Square brackets in String.prototype.search() in JavascriptJavascript 中 String.prototype.search() 中的方括号
【发布时间】: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


【解决方案1】:

如果在 String.prototype.search() 中使用字符串作为参数,则该字符串始终会转换为正则表达式。

var result1 = text.search('[the] needle');

等同于

var result1 = text.search(/[the] needle/);

为了搜索一个字符串,你必须使用String.prototype.indexOf():

var result3 = text.indexOf('[haystick]');     // 16

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-02-22
    • 2022-11-19
    • 2020-07-05
    • 2011-07-05
    • 1970-01-01
    相关资源
    最近更新 更多