Symbol.split - JavaScript | MDN (original) (raw)

Try it

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"

Value

The well-known symbol Symbol.split.

Property attributes of Symbol.split
Writable no
Enumerable no
Configurable no

Examples

Custom reverse split

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" ]

Specifications

Specification
ECMAScript® 2026 Language Specification # sec-symbol.split

Browser compatibility

See also