RegExp.prototype[Symbol.search]()

Baseline 已广泛支持

此特性已非常成熟,可在多种设备和浏览器版本上使用。自 ⁨2016 年 9 月⁩以来,它已在各大浏览器中可用。

[Symbol.search]() 方法是 RegExp 实例上的一种方法,它定义了 String.prototype.search 的行为。

试一试

class RegExp1 extends RegExp {
  constructor(str) {
    super(str);
    this.pattern = str;
  }
  [Symbol.search](str) {
    return str.indexOf(this.pattern);
  }
}

console.log("table football".search(new RegExp1("foo")));
// Expected output: 6

语法

js
regexp[Symbol.search](str)

参数

str

要搜索的目标 String

返回值

正则表达式与给定字符串的第一个匹配项的索引,如果未找到匹配项,则为 -1

描述

此方法由 String.prototype.search() 在内部调用。例如,以下两个示例返回相同的结果。

js
"abc".search(/a/);

/a/[Symbol.search]("abc");

此方法不像 [Symbol.split]()[Symbol.matchAll]() 那样复制正则表达式。然而,与 [Symbol.match]()[Symbol.replace]() 不同,它会在执行开始时将 lastIndex 设置为 0,并在退出时将其恢复到先前的值,从而通常避免副作用。这意味着 g 标志对此方法无效,即使 lastIndex 非零,它也始终返回字符串中的第一个匹配项。这也意味着粘性正则表达式将始终严格地在字符串开头进行搜索。

js
const re = /[abc]/g;
re.lastIndex = 2;
console.log("abc".search(re)); // 0

const re2 = /[bc]/y;
re2.lastIndex = 1;
console.log("abc".search(re2)); // -1
console.log("abc".match(re2)); // [ 'b' ]

[Symbol.search]() 始终只调用一次正则表达式的 exec() 方法,并返回结果的 index 属性,如果结果为 null,则返回 -1

此方法用于自定义 RegExp 子类中的搜索行为。

示例

直接调用

此方法几乎可以与 String.prototype.search() 以相同的方式使用,只是 this 的值和参数顺序不同。

js
const re = /-/g;
const str = "2016-01-02";
const result = re[Symbol.search](str);
console.log(result); // 4

在子类中使用 [Symbol.search]()

RegExp 的子类可以覆盖 [Symbol.search]() 方法来修改其行为。

js
class MyRegExp extends RegExp {
  constructor(str) {
    super(str);
    this.pattern = str;
  }
  [Symbol.search](str) {
    return str.indexOf(this.pattern);
  }
}

const re = new MyRegExp("a+b");
const str = "ab a+b";
const result = str.search(re); // String.prototype.search calls re[Symbol.search]().
console.log(result); // 3

规范

规范
ECMAScript® 2026 语言规范
# sec-regexp.prototype-%symbol.search%

浏览器兼容性

另见