String.prototype.matchAll()
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 método matchAll() retorna um iterador de todos os resultados correspondentes a uma string em relação a uma expressão regular, incluindo grupos de captura.
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)
Parâmetros
Valor retornado
Um iterador (que não é um iterável reinicializável).
Exemplos
>Regexp.exec() e matchAll()
Antes da adição do matchAll() ao JavaScript, era possível usar chamadas regexp.exec (e regexes com a sinalização (flag) /g) em um loop para obter todas as correspondências:
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]} início=${match.index} fim=${regexp.lastIndex}.`, ); // retorna "Encontrou football início=6 fim=14." // retorna "Encontou foosball início=16 fim=24." } Com o matchAll() disponível, você pode evitar o loop while e executar com g.
Em vez disso, usando o matchAll(), você obtém um iterador para usar com o mais conveniente for...of, array spread ou construções Array.from():
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]} início=${match.index} fim=${ match.index + match[0].length }.`, ); } // retorna "Encontrou football início=6 fim=14." // retorna "Encontrou foosball início=16 fim=24." // O iterador de correspondências se esgota após a iterção for..of // Chame matchAll novamente para criar um novo iterador Array.from(str.matchAll(regexp), (m) => m[0]); // Array [ "football", "foosball" ] matchAll() retornará uma exceção se o sinalizador (flag) g estiver ausente.
const regexp = RegExp("[a-c]", ""); const str = "abc"; str.matchAll(regexp); // retorna TypeError matchAll() cria internamente um clone da regexp - portanto, ao contrário de regexp.exec(), o lastIndex não muda conforme a string é verificada.
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 razão convincente para usar matchAll() é o acesso aprimorado para capturar grupos.
Os grupos de captura são ignorados ao usar match() com o sinalizador global /g:
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:
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] Especificações
| Specification |
|---|
| ECMAScript® 2026 Language Specification> # sec-string.prototype.matchall> |