RegExp.prototype[@@split]()

RegExp 实例的 [@@split]() 方法指定当正则表达式作为分隔符传入时 String.prototype.split 的行为方式。

¥The [@@split]() method of RegExp instances specifies how String.prototype.split should behave when the regular expression is passed in as the separator.

Try it

语法

¥Syntax

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

参数

¥Parameters

str

分割操作的目标。

limit Optional

整数,指定要查找的拆分数量的限制。[@@split]() 方法仍然在 this RegExp 模式(或者在上面的语法中为 regexp)的每次匹配上进行拆分,直到拆分项的数量与 limit 匹配或字符串不符合 this 模式。

返回值

¥Return value

包含子字符串作为其元素的 Array。包括捕获组。

¥An Array containing substrings as its elements. Capturing groups are included.

描述

¥Description

RegExp 作为分隔符传递时,会在 String.prototype.split() 内部调用此方法。例如,以下两个示例返回相同的结果。

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

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

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

该方法用于自定义 RegExp 子类中 split() 的行为。

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

RegExp.prototype[@@split]() 基本方法表现出以下行为:

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

  • 它首先使用 @@species 构造一个新的正则表达式,从而避免以任何方式改变原始正则表达式。
  • 正则表达式的 g ("global") 标志将被忽略,并且始终应用 y ("sticky") 标志,即使它最初不存在也是如此。
  • 如果目标字符串为空,并且正则表达式可以匹配空字符串(例如,/a?/),则返回空数组。否则,如果正则表达式无法匹配空字符串,则返回 [""]
  • 通过连续调用 this.exec() 进行匹配。由于正则表达式始终是粘性的,因此它将沿着字符串移动,每次都会生成匹配的字符串、索引和任何捕获组。
  • 对于每个匹配,最后一个匹配字符串的末尾和当前匹配字符串的开头之间的子字符串首先附加到结果数组中。然后,捕获组的值被一一附加。
  • 如果当前匹配是空字符串,或者正则表达式在当前位置不匹配(因为它是粘性的),则 lastIndex 仍将前进 - 如果正则表达式是 Unicode 感知,它将前进一个 Unicode 代码点;否则,前进一个 UTF-16 代码单元。
  • 如果正则表达式与目标字符串不匹配,则目标字符串按原样返回,并封装在数组中。
  • 返回的数组的长度永远不会超过 limit 参数(如果提供),同时尝试尽可能接近。因此,如果数组已填满,则最后一个匹配项及其捕获组可能不会全部出现在返回的数组中。

示例

¥Examples

直接致电

¥Direct call

该方法的使用方式与 String.prototype.split() 几乎相同,除了 this 不同以及参数顺序不同之外。

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

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

在子类中使用@@split

¥Using @@split in subclasses

RegExp 的子类可以重写 [@@split]() 方法来修改默认行为。

¥Subclasses of RegExp can override the [@@split]() method to modify the default behavior.

js
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[@@split].
console.log(result); // ["(2016)", "(01)", "(02)"]

规范

Specification
ECMAScript Language Specification
# sec-regexp.prototype-@@split

¥Specifications

浏览器兼容性

BCD tables only load in the browser

¥Browser compatibility

也可以看看