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

浏览器兼容性

另见