[ Web Proxy ]
URL:
Viewing: https://developer.mozilla.org/pt-BR/docs/Web/JavaScript/Reference/Global_Objects/String/matchAll [Back]  [Original]

String.prototype.matchAll() - JavaScript | MDN

Esta pgina foi traduzida do ingls pela comunidade. Saiba mais e junte-se comunidade MDN Web Docs.

View in English Always switch to English

String.prototype.matchAll()

Baseline Widely available

This feature is well established and works across many devices and browser versions. Its been available across browsers since janeiro de 2020.

O mtodo matchAll() retorna um iterador de todos os resultados correspondentes a uma string em relao a uma expresso regular, incluindo grupos de captura.

In this article

Experimente

const regexp = /t(e)(st(\d?))/g;
const str = "test1test2";

const array = [...str.matchAll(regexp)];

console.log(array[0]);
// Expected output: Array ["test1", "e", "st1", "1"]

console.log(array[1]);
// Expected output: Array ["test2", "e", "st2", "2"]

Sintaxe

str.matchAll(regexp)

Parmetros

regexp

Um objeto de expresso regular.

Se um objeto obj no-RegExp for passado, ele ser convertido implicitamente em um RegExp usando new RegExp(obj).

O objeto RegExp deve ter o sinalizador (flag) /g, caso contrrio, um TypeError ser retornado.

Valor retornado

Um iterador (que no um itervel reinicializvel).

Exemplos

Regexp.exec() e matchAll()

Antes da adio do matchAll() ao JavaScript, era possvel usar chamadas regexp.exec (e regexes com a sinalizao (flag) /g) em um loop para obter todas as correspondncias:

js
const regexp = RegExp("foo[a-z]*", "g");
const str = "table football, foosball";
let match;

while ((match = regexp.exec(str)) !== null) {
  console.log(
    `Encontrou ${match[0]} incio=${match.index} fim=${regexp.lastIndex}.`,
  );
  // retorna "Encontrou football incio=6 fim=14."
  // retorna "Encontou foosball incio=16 fim=24."
}

Com o matchAll() disponvel, voc pode evitar o loop while e executar com g.

Em vez disso, usando o matchAll(), voc obtm um iterador para usar com o mais conveniente for...of, array spread ou construes Array.from():

js
const regexp = RegExp("foo[a-z]*", "g");
const str = "table football, foosball";
const matches = str.matchAll(regexp);

for (const match of matches) {
  console.log(
    `Encontrou ${match[0]} incio=${match.index} fim=${
      match.index + match[0].length
    }.`,
  );
}
// retorna "Encontrou football incio=6 fim=14."
// retorna "Encontrou foosball incio=16 fim=24."

// O iterador de correspondncias se esgota aps a itero for..of
// Chame matchAll novamente para criar um novo iterador
Array.from(str.matchAll(regexp), (m) => m[0]);
// Array [ "football", "foosball" ]

matchAll() retornar uma exceo se o sinalizador (flag) g estiver ausente.

js
const regexp = RegExp("[a-c]", "");
const str = "abc";
str.matchAll(regexp);
// retorna TypeError

matchAll() cria internamente um clone da regexp - portanto, ao contrrio de regexp.exec(), o lastIndex no muda conforme a string verificada.

js
const regexp = RegExp("[a-c]", "g");
regexp.lastIndex = 1;
const str = "abc";
Array.from(str.matchAll(regexp), (m) => `${regexp.lastIndex} ${m[0]}`);
// Array [ "1 b", "1 c" ]

Melhor acesso para capturar grupos (do que String.prototype.match())

Outra razo convincente para usar matchAll() o acesso aprimorado para capturar grupos.

Os grupos de captura so ignorados ao usar match() com o sinalizador global /g:

js
let regexp = /t(e)(st(\d?))/g;
let str = "test1test2";

str.match(regexp);
// Array ['test1', 'test2']

Usando o matchAll(), voc pode acessar os grupos de captura facilmente:

js
let array = [...str.matchAll(regexp)];

array[0];
// ['test1', 'e', 'st1', '1', index: 0, input: 'test1test2', length: 4]
array[1];
// ['test2', 'e', 'st2', '2', index: 5, input: 'test1test2', length: 4]

Especificaes

Specification
ECMAScript 2027 LanguageSpecification
# sec-string.prototype.matchall

Compatibilidade com navegadores

Veja tambm


Web Proxy Viewer  |  New URL  |  Original Page