Symbol.search

Baseline 已廣泛支援

此特性已相當成熟,可在許多裝置和瀏覽器版本上使用。自 ⁨2020 年 1 月⁩ 起,所有主流瀏覽器均已支援。

Symbol.search 靜態資料屬性表示 知名符號 Symbol.searchString.prototype.search() 方法在其第一個引數上查詢此符號,以查詢返回與當前物件匹配的字串內的索引的方法。

有關更多資訊,請參閱 RegExp.prototype[Symbol.search]()String.prototype.search()

試一試

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

console.log("foobar".search(new Search1("bar")));
// Expected output: 3

知名符號 Symbol.search

Symbol.search 的屬性特性
可寫
可列舉
可配置

示例

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

console.log("foobar".search(new CaseInsensitiveSearch("BaR"))); // 3

規範

規範
ECMAScript® 2026 語言規範
# sec-symbol.search

瀏覽器相容性

另見