The [@@split]() method splits a String object into an array of strings by separating the string into substrings.
The source for this interactive example is stored in a GitHub repository. If you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
Syntax
regexp[Symbol.split](str[, limit])
Parameters
str- The target of the split operation.
limitOptional-
Integer specifying a limit on the number of splits to be found. The
[@@split]()method still splits on every match ofthisRegExp pattern (or, in the Syntax above,regexp), until the number of split items match thelimitor the string falls short ofthispattern.
Return value
An Array containing substrings as its elements.
Description
This method is called internally in String.prototype.split() if its separator argument is an object that has a @@split method, such as a RegExp. 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 subclass.
Examples
Direct call
This method can be used in almost the same way as String.prototype.split(), except the different this and the different order of arguments.
let re = /-/g; let str = '2016-01-02'; let result = re[Symbol.split](str); console.log(result); // ["2016", "01", "02"]
Using @@split in subclasses
Subclasses of RegExp can override the [@@split]() method to modify the default behavior.
class MyRegExp extends RegExp {
[Symbol.split](str, limit) {
let result = RegExp.prototype[Symbol.split].call(this, str, limit);
return result.map(x => "(" + x + ")");
}
}
let re = new MyRegExp('-');
let str = '2016-01-02';
let result = str.split(re); // String.prototype.split calls re[@@split].
console.log(result); // ["(2016)", "(01)", "(02)"]
Specifications
| Specification |
|---|
| ECMAScript (ECMA-262) The definition of 'RegExp.prototype[@@split]' in that specification. |
Browser compatibility
| Desktop | Mobile | Server | |||||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
@@split | Chrome Full support 50 | Edge Full support 79 | Firefox Full support 49 | IE No support No | Opera Full support 37 | Safari Full support 10 | WebView Android Full support 50 | Chrome Android Full support 50 | Firefox Android Full support 49 | Opera Android Full support 37 | Safari iOS Full support 10 | Samsung Internet Android Full support 5.0 | nodejs Full support 6.0.0 |
Legend
- Full support
- Full support
- No support
- No support
