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%

瀏覽器相容性

另見