In an instance of a custom RegExp
subclass, such as MyRegExp
, the MyRegExp
species is the MyRegExp
constructor. However, you might want to overwrite this, in order to return parent RegExp
objects in your derived class methods:
class MyRegExp extends RegExp {
// Overwrite MyRegExp species to the parent RegExp constructor
static get [Symbol.species]() {
return RegExp;
}
}
Or you can use this to observe the copying process:
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