Movatterモバイル変換


[0]ホーム

URL:


  1. Tecnologia Web para desenvolvedores
  2. JavaScript
  3. Referência JavaScript
  4. Objetos Globais
  5. String
  6. String.prototype.matchAll()

Esta página foi traduzida do inglês pela comunidade.Saiba mais e junte-se à comunidade MDN Web Docs.

View in EnglishAlways switch to English

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.

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

regexp

Um objeto de expressão regular.

Se um objetoobj não-RegExp for passado, ele será convertido implicitamente em umRegExp usandonew RegExp(obj).

O objetoRegExp deve ter o sinalizador (flag)/g, caso contrário, umTypeError será retornado.

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:

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]} 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():

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]} 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.

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

matchAll() cria internamente um clone daregexp - portanto, ao contrário deregexp.exec(), olastIndex não 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 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:

js
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:

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]

Especificações

Specification
ECMAScript® 2026 Language Specification
# sec-string.prototype.matchall

Compatibilidade com navegadores

Veja também

Help improve MDN

Learn how to contribute

This page was last modified on byMDN contributors.


[8]ページ先頭

©2009-2025 Movatter.jp