Symbol.search

Symbol.search 指定了一个搜索方法,这个方法接受用户输入的正则表达式,返回该正则表达式在字符串中匹配到的下标,这个方法由以下的方法来调用 String.prototype.search()

更多信息请参见 RegExp.prototype[@@search]()String.prototype.search().

Symbol.search 的属性特性
可写
可枚举
可配置

案例

自定义字符串搜索

class caseInsensitiveSearch {
  constructor(value) {
    this.value = value.toLowerCase();
  }
  [Symbol.search](string) {
    return string.toLowerCase().indexOf(this.value);
  }
}

console.log('foobar'.search(new caseInsensitiveSearch('BaR')));
// expected output: 3

规范

Specification
ECMAScript Language Specification
# sec-symbol.search

浏览器兼容性

BCD tables only load in the browser

参见