| [ Web Proxy ] |
| Viewing: https://developer.mozilla.org/es/docs/Web/JavaScript/Reference/Global_Objects/String/matchAll | [Back] [Original] |
Get to know MDN better
Esta pgina ha sido traducida del ingls por la comunidad. Aprende ms y nete a la comunidad de MDN Web Docs.
This feature is well established and works across many devices and browser versions. Its been available across browsers since enero de 2020.
El mtodo matchAll() retorna un iterador de todos los resultados de ocurrencia en una cadena de texto contra una expresin regular, incluyendo 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"]
cadena.matchAll(expresionRegular)
Un objeto expresin regular. Si se pasa un objeto no-RegExp obj, este es implcitamente convertido a RegExp va new RegExp(obj).
Un iterador (el cual no es reiniciable).
Antes de la adicin de matchAll a JavaScript, fue posible hacer llamados a regexp.exec (y usar expresiones regulares con la bandera /g) en un ciclo para obtener las ocurrencias:
const regexp = RegExp("foo[a-z]*", "g");
const cadena = "mesa football, foosball";
let ocurrencia;
while ((ocurrencia = regexp.exec(cadena)) !== null) {
console.log(
`Encontrado ${ocurrencia[0]} inicio=${ocurrencia.index} final=${regexp.lastIndex}.`,
);
// salida esperada: "Encontrado football inicio=5 final=13."
// salida esperada: "Encontrado foosball inicio=15 final=23."
}
Con matchAll disponible, puedes evitar el ciclo while y exec con /g. Por el contrario, usando matchAll, obtienes un iterador con el cual puedes usar con constructores ms convenientes for...of, array spread, o Array.from():
const regexp = RegExp("foo[a-z]*", "g");
const cadena = "mesa football, foosball";
const ocurrencias = cadena.matchAll(regexp);
for (const ocurrencia of ocurrencias) {
console.log(
`Encontrado ${ocurrencia[0]} inicio=${ocurrencia.index} final=${
ocurrencia.index + ocurrencia[0].length
}.`,
);
}
// salida esperada: "Encontrado football start=5 end=13."
// salida esperada: "Encontrado foosball start=15 end=23."
// el iterador ocurrencias es agotado despus de la iteracin for..of
// Llama matchAll de nuevo para crear un nuevo iterador
Array.from(cadena.matchAll(regexp), (m) => m[0]);
// Array [ "football", "foosball" ]
matchAll solo devuelve la primer ocurrencia si la bandera /g est ausente.
const regexp = RegExp("[a-c]", "");
const cadena = "abc";
Array.from(cadena.matchAll(regexp), (m) => m[0]);
// Array [ "a" ]
matchAll internamente hace un clon de la expresin regular, entonces a diferencia de regexp.exec, lastIndex no cambia a medida que la cadena es escaneada.
const regexp = RegExp("[a-c]", "g");
regexp.lastIndex = 1;
const cadena = "abc";
Array.from(cadena.matchAll(regexp), (m) => `${regexp.lastIndex} ${m[0]}`);
// Array [ "1 b", "1 c" ]
Otra buena razn para matchAll es el mejorado acceso a los grupos de captura. Los grupos de captura son ignorados cuando se usa match() con la bandera global /g:
var regexp = /t(e)(st(\d?))/g;
var cadena = "test1test2";
cadena.match(regexp);
// Array ['test1', 'test2']
Con matchAll puedes acceder a ellos:
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 |
This page was last modified on 11 feb 2025 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()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()trimStart()String.prototype.valueOf()[Symbol.iterator]()Object/FunctionYour 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 |