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% |
浏览器兼容性
加载中…