Esta página foi traduzida do inglês pela comunidade.Saiba mais e junte-se à comunidade MDN Web Docs.
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étodomatchAll() retorna um iterador de todos os resultados correspondentes a uma string em relação a umaexpressão regular, incluindogrupos 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)
Parâmetros
Valor retornado
Umiterador (que não é um iterável reinicializável).
Exemplos
>Regexp.exec() e matchAll()
Antes da adição domatchAll() ao JavaScript, era possível usar chamadasregexp.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 omatchAll() disponível, você pode evitar o loopwhile e executar comg.
Em vez disso, usando omatchAll(), você obtém um iterador para usar com o mais convenientefor...of,array spread ou construçõesArray.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 iteradorArray.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 TypeErrormatchAll() cria internamente um clone daregexp - portanto, ao contrário deregexp.exec(), olastIndex 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 usarmatchAll() é o acesso aprimorado para capturar grupos.
Os grupos de captura são ignorados ao usarmatch() com o sinalizador global/g:
let regexp = /t(e)(st(\d?))/g;let str = "test1test2";str.match(regexp);// Array ['test1', 'test2']Usando omatchAll(), 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> |