Symbol.match
Baseline Widely available
This feature is well established and works across many devices and browser versions. It’s been available across browsers since September 2015.
El símbolo conocido como Symbol.match
especifica la coincidencia de una expresión regular con una cadena. Esta función es llamada por el método String.prototype.match()
.
Pruébalo
const regexp1 = /foo/;
// console.log('/foo/'.startsWith(regexp1));
// Expected output (Chrome): Error: First argument to String.prototype.startsWith must not be a regular expression
// Expected output (Firefox): Error: Invalid type: first can't be a Regular Expression
// Expected output (Safari): Error: Argument to String.prototype.startsWith cannot be a RegExp
regexp1[Symbol.match] = false;
console.log("/foo/".startsWith(regexp1));
// Expected output: true
console.log("/baz/".endsWith(regexp1));
// Expected output: false
Descripción
Esta función también se utiliza para identificar si los objetos tienen el comportamiento de las expresiones regulares. Por ejemplo, los métodos String.prototype.startsWith()
, String.prototype.endsWith()
y String.prototype.includes()
, comprueban si su primer argumento es una expresión regular y lanzarán un TypeError
si lo son. Ahora bien, si el símbolo match
se establece como false
(o un valor Falsy), indica que el objeto no está destinado a ser utilizado como un objeto de expresión regular.
Atributos de la propiedad Symbol.match | |
---|---|
Sobrescribir | No |
Numerable | No |
Configurable | No |
Ejemplos
Desactivar la comprobación de isRegExp
El siguiente código lanzará un TypeError
:
"/bar/".startsWith(/bar/);
// Lanza TypeError, ya que /bar/ es una expresión regular
// y Symbol.match no se modifica.
Sin embargo, si establece Symbol.match
a false
, la comprobación isRegExp
(que utiliza la propiedad match
) indicará que el objeto no es un objeto de expresión regular. Los métodos startsWith
y endsWith
no lanzarán un TypeError
como consecuencia.
const re = /foo/;
re[Symbol.match] = false;
"/foo/".startsWith(re); // true
"/baz/".endsWith(re); // false
Especificaciones
Specification |
---|
ECMAScript® 2025 Language Specification # sec-symbol.match |
Compatibilidad con navegadores
Report problems with this compatibility data on GitHubdesktop | mobile | server | ||||||||||||
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
match |
Legend
Tip: you can click/tap on a cell for more information.
- Full support
- Full support