| [ Web Proxy ] |
| Viewing: https://developer.mozilla.org/pt-BR/docs/Web/JavaScript/Reference/Global_Objects/String/matchAll | [Back] [Original] |
Get to know MDN better
Esta pgina foi traduzida do ingls pela comunidade. Saiba mais e junte-se comunidade MDN Web Docs.
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.
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"]
str.matchAll(regexp)
regexpUm 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.
Um iterador (que no um itervel reinicializvel).
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:
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():
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.
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.
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" ]
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:
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]
| Specification |
|---|
| ECMAScript 2027 LanguageSpecification # sec-string.prototype.matchall |
String.prototype.match()RegExpRegExp.prototype.exec()RegExp.prototype.test()This page was last modified on 22 de mai. de 2026 by MDN contributors.
StringString.prototype.anchor()at()String.prototype.big()String.prototype.blink()String.prototype.bold()String.prototype.charAt()String.prototype.charCodeAt()String.prototype.codePointAt()String.prototype.concat()String.prototype.endsWith()String.prototype.fixed()String.prototype.fontcolor()String.prototype.fontsize()String.prototype.includes()String.prototype.indexOf()isWellFormed()String.prototype.italics()String.prototype.lastIndexOf()String.prototype.link()String.prototype.localeCompare()String.prototype.match()String.prototype.matchAll()String.prototype.normalize()String.prototype.padEnd()String.prototype.padStart()String.prototype.repeat()String.prototype.replace()String.prototype.replaceAll()String.prototype.search()String.prototype.slice()String.prototype.small()String.prototype.split()String.prototype.startsWith()String.prototype.strike()String.prototype.sub()String.prototype.substr()String.prototype.substring()String.prototype.sup()String.prototype.toLocaleLowerCase()String.prototype.toLocaleUpperCase()String.prototype.toLowerCase()String.prototype.toString()String.prototype.toUpperCase()toWellFormed()String.prototype.trim()String.prototype.trimEnd()String.prototype.trimStart()String.prototype.valueOf()String.prototype[@@iterator]()Object/FunctionObject.prototype.__defineGetter__()Object.prototype.__defineSetter__()Object.prototype.__lookupGetter__()Object.prototype.__lookupSetter__()Object.prototype.hasOwnProperty()Object.prototype.isPrototypeOf()Object.prototype.propertyIsEnumerable()Object.prototype.toLocaleString()Object.prototype.toString()Object.prototype.valueOf()Your blueprint for a better internet.
Portions of this content are 19982026 by individual mozilla.org contributors. Content available under a Creative Commons license.
| Web Proxy Viewer | New URL | Original Page |