This page was translated from English by the community.Learn more and join the MDN Web Docs community.
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 январь 2020 г..
МетодmatchAll() возвращает итератор по всем результатам при сопоставлениистроки с регулярным выражением.
In this article
Интерактивный пример
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)
Параметры
Возвращаемое значение
Возвращаетсяiterator (не перезапускаемый).
Примеры
>Regexp.exec() и matchAll()
До добавления методаmatchAll в JavaScript, можно было использовать методregexp.exec (и регулярные выражения с флагом/g ) в цикле для получения доступа к совпадениям:
const regexp = RegExp("foo*", "g");const str = "table football, foosball";while ((matches = regexp.exec(str)) !== null) { console.log(`Found ${matches[0]}. Next starts at ${regexp.lastIndex}.`); // expected output: "Found foo. Next starts at 9." // expected output: "Found foo. Next starts at 19."}С появлениемmatchAll, нет необходимости использовать циклwhile и методexec с флагом/g.Используя вместо этого методmatchAll, вы получаете итератор, который вы можете использовать более удобно с конструкциямиfor...of,array spread, илиArray.from() :
const regexp = RegExp("foo*", "g");const str = "table football, foosball";let matches = str.matchAll(regexp);for (const match of matches) { console.log(match);}// Array [ "foo" ]// Array [ "foo" ]// итерация больше недоступна после вызова for of// Для создания нового итератора вызовите matchAll повторноmatches = str.matchAll(regexp);Array.from(matches, (m) => m[0]);// Array [ "foo", "foo" ]Улучшенный доступ к группам захвата
Ещё одна веская причина использоватьmatchAll это улучшенный доступ к группам захвата. Группы захвата игнорируются при использованииmatch() с глобальным флагом/g:
var regexp = /t(e)(st(\d?))/g;var str = "test1test2";str.match(regexp);// Array ['test1', 'test2']СmatchAll у вас появляется к ним доступ:
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® 2026 Language Specification> # sec-string.prototype.matchall> |