此页面由社区从英文翻译而来。了解更多并加入 MDN Web Docs 社区。

View in English Always switch to English

Symbol.split

基线 广泛可用

自 2020年1月 起,此特性已在主流浏览器中得到支持,可在大多数设备和浏览器版本中正常使用。

Symbol.split 指向一个正则表达式的索引处分割字符串的方法。这个方法通过 String.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® 2027 Language Specification
# sec-symbol.split

浏览器兼容性

参阅