[@@split]() 方法切割 String 对象为一个其子字符串的数组 。
regexp[Symbol.split](str[, limit])
strlimit可选。一个为了限制切割数量的特定整数。 [@@split]() 防范仍会切割每个匹配正则模式的匹配项,直到切割数量达到该限制数,除非提前切割完字符串。
包含其子字符串的Array 。
如果切割器是一个RegExp对象,这个方法就将在 String.prototype.split() 的内部调用。例如,下面的两个方法返回相同结果。
'a-b-c'.split(/-/);
/-/[Symbol.split]('a-b-c');
这个方法为自定义 RegExp 子类中的匹配行为而存在。
如果str参数不是一个RegExp 对象, String.prototype.split() 就不会调用该方法,也不会创建一个 RegExp 对象。示例
这个方法的使用方式和 String.prototype.split() 相同,不同之处是 this 和参数顺序。
var re = /-/g;
var str = '2016-01-02';
var result = re[Symbol.split](str);
console.log(result); // ["2016", "01", "02"]
@@splitRegExp 的子类可以覆写 [@@split]()方法来修改默认行为。
class MyRegExp extends RegExp {
[Symbol.split](str, limit) {
var result = RegExp.prototype[Symbol.split].call(this, str, limit);
return result.map(x => "(" + x + ")");
}
}
var re = new MyRegExp('-');
var str = '2016-01-02';
var result = str.split(re); // String.prototype.split calls re[@@split].
console.log(result); // ["(2016)", "(01)", "(02)"]
| Specification | Status | Comment |
|---|---|---|
| ECMAScript 2015 (6th Edition, ECMA-262) RegExp.prototype[@@split] |
Standard | 初始定义 |
| ECMAScript Latest Draft (ECMA-262) RegExp.prototype[@@split] |
Draft |
| Feature | Chrome | Firefox (Gecko) | Internet Explorer | Opera | Safari |
|---|---|---|---|---|---|
| Basic support | ? | 49 (49) | ? | ? | ? |
| Feature | Android | Chrome for Android | Firefox Mobile (Gecko) | IE Mobile | Opera Mobile | Safari Mobile |
|---|---|---|---|---|---|---|
| Basic support | ? | ? | 49.0 (49) | ? | ? | ? |