RegExp.prototype[Symbol.search]()
[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)
引數
返回值
正則表示式與給定字串的第一個匹配項的索引,如果未找到匹配項,則為 -1。
描述
此方法由 在內部呼叫。例如,以下兩個示例返回相同的結果。String.prototype.search()
js
"abc".search(/a/);
/a/[Symbol.search]("abc");
此方法不像 或 [Symbol.split]() 那樣複製正則表示式。然而,與 [Symbol.matchAll]() 或 [Symbol.match]() 不同,它會在執行開始時將 [Symbol.replace]() 設定為 0,並在退出時將其恢復到先前的值,從而通常避免副作用。這意味著 lastIndexg 標誌對此方法無效,即使 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% |
瀏覽器相容性
載入中…