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 janeiro de 2020.
O símbolo Symbol.match é conhecido por especificar a compatibilidade de uam expressão regular contra uma string. Essa função é chamada pelo método String.prototype.match().
Experimente
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
Descrição
Essa função também é usada para identificar se um objeto tem o comportamento de uma expressão regular. Por exemplo, os métodos String.prototype.startsWith(), String.prototype.endsWith() e String.prototype.includes(), verificar se o primeiro agumento é uma expressão regular e irá lançar um TypeError se eles forém. Agora, se o símbolo match é configurado para false (ou um valor Falsy ), ele indica que o objeto não tem intensão de ser usado como um ojbeto de expressão regular
Property attributes of Symbol.match | |
|---|---|
| Writable | no |
| Enumerable | no |
| Configurable | no |
Exemplos
>Desativando a verificação isRegExp
O seguinte código vai lançar um TypeError:
"/bar/".startsWith(/bar/);
// Lança um TypeError, como /bar/ é uma expressão regular
// não Symbol.match não é modificado.
Entretanto, se você configurar Symbol.match para false, a verificação isRegExp (que usa a propriedade match ) que o objeto não é uma expressão regular. O método startsWith e endsWith não vão lançar um TypeError como consequência.
var re = /foo/;
re[Symbol.match] = false;
"/foo/".startsWith(re); // true
"/baz/".endsWith(re); // false
Especificações
| Specification |
|---|
| ECMAScript® 2026 Language Specification> # sec-symbol.match> |
Compatibilidade com navegadores
Loading…