RegExp.prototype[@@split]() - JavaScript 编辑

The [@@split]() method splits a String object into an array of strings by separating the string into substrings.

Syntax

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

Parameters

str
The target of the split operation.
limit Optional

Integer specifying a limit on the number of splits to be found. The [@@split]() method still splits on every match of this RegExp pattern (or, in the Syntax above, regexp), until the number of split items match the limit or the string falls short of this pattern.

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

BCD tables only load in the browser

See also

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据

词条统计

浏览:98 次

字数:5657

最后编辑:6 年前

编辑次数:0 次

    我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
    原文