Symbol.split

Baseline 已廣泛支援

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

Symbol.split 靜態資料屬性代表 著名符號 Symbol.splitString.prototype.split() 方法會在其第一個引數上查詢此符號,以用於在匹配當前物件的索引處拆分字串的方法。

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

試一試

class Split1 {
  constructor(value) {
    this.value = value;
  }
  [Symbol.split](string) {
    const index = string.indexOf(this.value);
    return `${this.value}${string.substring(0, index)}/${string.substring(
      index + this.value.length,
    )}`;
  }
}

console.log("foobar".split(new Split1("foo")));
// Expected output: "foo/bar"

著名符號 Symbol.split

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

示例

自定義反向分割

js
class ReverseSplit {
  [Symbol.split](string) {
    const array = string.split(" ");
    return array.reverse();
  }
}

console.log("Another one bites the dust".split(new ReverseSplit()));
// [ "dust", "the", "bites", "one", "Another" ]

規範

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

瀏覽器相容性

另見