docs.rodeo

MDN Web Docs mirror

RegExp.prototype[Symbol.split]()

{{JSRef}} 

The [Symbol.split]() method of {{jsxref("RegExp")}}  instances specifies how String.prototype.split should behave when the regular expression is passed in as the separator.

{{InteractiveExample("JavaScript Demo: RegExp.prototype[Symbol.split]()")}} 

class RegExp1 extends RegExp {
  [Symbol.split](str, limit) {
    const result = RegExp.prototype[Symbol.split].call(this, str, limit);
    return result.map((x) => `(${x})`);
  }
}

console.log("2016-01-02".split(new RegExp1("-")));
// Expected output: Array ["(2016)", "(01)", "(02)"]

console.log("2016-01-02".split(new RegExp("-")));
// Expected output: Array ["2016", "01", "02"]

Syntax

regexp[Symbol.split](str)
regexp[Symbol.split](str, limit)

Parameters

Return value

An {{jsxref("Array")}}  containing substrings as its elements. Capturing groups are included.

Description

This method is called internally in {{jsxref("String.prototype.split()")}}  when a RegExp is passed as the separator. For example, the following two examples return the same result.

"a-b-c".split(/-/);

/-/[Symbol.split]("a-b-c");

This method exists for customizing the behavior of split() in RegExp subclasses.

The RegExp.prototype[Symbol.split]() base method exhibits the following behaviors:

Examples

Direct call

This method can be used in almost the same way as {{jsxref("String.prototype.split()")}} , except the different this and the different order of arguments.

const re = /-/g;
const str = "2016-01-02";
const result = re[Symbol.split](str);
console.log(result); // ["2016", "01", "02"]

Using [Symbol.split]() in subclasses

Subclasses of {{jsxref("RegExp")}}  can override the [Symbol.split]() method to modify the default behavior.

class MyRegExp extends RegExp {
  [Symbol.split](str, limit) {
    const result = RegExp.prototype[Symbol.split].call(this, str, limit);
    return result.map((x) => `(${x})`);
  }
}

const re = new MyRegExp("-");
const str = "2016-01-02";
const result = str.split(re); // String.prototype.split calls re[Symbol.split]().
console.log(result); // ["(2016)", "(01)", "(02)"]

Specifications

{{Specifications}} 

Browser compatibility

{{Compat}} 

See also

In this article

View on MDN