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 January 2020.
Метод matchAll()
возвращает итератор по всем результатам при сопоставлении строки с регулярным выражением.
Интерактивный пример
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® 2025 Language Specification # sec-string.prototype.matchall |
Совместимость с браузерами
Report problems with this compatibility data on GitHubdesktop | mobile | server | ||||||||||||
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
matchAll |
Legend
Tip: you can click/tap on a cell for more information.
- Full support
- Full support