[@@split]() 方法切割 String 对象为一个其子字符串的数组 。
语法
regexp[Symbol.split](str[, limit])
参数
-
str - 切割操作的目标字符串
-
limit -
可选。一个为了限制切割数量的特定整数。
[@@split]()防范仍会切割每个匹配正则模式的匹配项,直到切割数量达到该限制数,除非提前切割完字符串。
返回值
包含其子字符串的Array 。
描述
如果切割器是一个String.prototype.split() 的内部调用。例如,下面的两个方法返回相同结果。
'a-b-c'.split(/-/);
/-/[Symbol.split]('a-b-c');
这个方法为自定义 RegExp 子类中的匹配行为而存在。
如果str参数不是一个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"]
在子类中使用 @@split
RegExp 的子类可以覆写 [@@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 |
浏览器兼容性
We're converting our compatibility data into a machine-readable JSON format. This compatibility table still uses the old format, because we haven't yet converted the data it contains.
Find out how you can help!
| 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) | ? | ? | ? |