RegExp[Symbol.species]

Baseline 已廣泛支援

此特性已非常成熟,可在多種裝置和瀏覽器版本上使用。自 ⁨2016 年 9 月⁩以來,它已在各大瀏覽器中可用。

RegExp[Symbol.species] 靜態訪問器屬性返回在某些 RegExp 方法中用於構造已複製的正則表示式的建構函式。

警告: [Symbol.species] 的存在允許執行任意程式碼,並可能產生安全漏洞。它還會使某些最佳化變得更加困難。引擎實現者正在 調查是否要移除此功能。如果可能,請避免依賴它。

語法

js
RegExp[Symbol.species]

返回值

呼叫 get [Symbol.species] 時建構函式 (this) 的值。返回值用於構造已複製的 RegExp 例項。

描述

[Symbol.species] 訪問器屬性返回 RegExp 物件的預設建構函式。子類建構函式可以覆蓋它以更改建構函式分配。預設實現基本上是

js
// Hypothetical underlying implementation for illustration
class RegExp {
  static get [Symbol.species]() {
    return this;
  }
}

由於這種多型實現,派生子類的 [Symbol.species] 預設情況下也將返回建構函式本身。

js
class SubRegExp extends RegExp {}
SubRegExp[Symbol.species] === SubRegExp; // true

某些 RegExp 方法會在執行 exec() 之前建立當前正則表示式例項的副本,以避免保留副作用,例如對 lastIndex 的更改。[Symbol.species] 屬性用於確定新例項的建構函式。複製當前正則表示式例項的方法是

示例

普通物件中的 species

[Symbol.species] 屬性返回預設建構函式,即 RegExp 物件的 RegExp 建構函式。

js
RegExp[Symbol.species]; // function RegExp()

派生物件中的 species

在自定義 RegExp 子類的例項中,例如 MyRegExpMyRegExp 的 species 是 MyRegExp 建構函式。但是,您可能希望覆蓋它,以便在派生類方法中返回父 RegExp 物件。

js
class MyRegExp extends RegExp {
  // Overwrite MyRegExp species to the parent RegExp constructor
  static get [Symbol.species]() {
    return RegExp;
  }
}

或者,您可以使用此方法來觀察複製過程。

js
class MyRegExp extends RegExp {
  constructor(...args) {
    console.log("Creating a new MyRegExp instance with args:", args);
    super(...args);
  }
  static get [Symbol.species]() {
    console.log("Copying MyRegExp");
    return this;
  }
  exec(value) {
    console.log("Executing with lastIndex:", this.lastIndex);
    return super.exec(value);
  }
}

Array.from("aabbccdd".matchAll(new MyRegExp("[ac]", "g")));
// Creating a new MyRegExp instance with args: [ '[ac]', 'g' ]
// Copying MyRegExp
// Creating a new MyRegExp instance with args: [ MyRegExp /[ac]/g, 'g' ]
// Executing with lastIndex: 0
// Executing with lastIndex: 1
// Executing with lastIndex: 2
// Executing with lastIndex: 5
// Executing with lastIndex: 6

規範

規範
ECMAScript® 2026 語言規範
# sec-get-regexp-%symbol.species%

瀏覽器相容性

另見