Movatterモバイル変換


[0]ホーム

URL:


MDN Web Docs

String.prototype.matchAll()

BaselineWidely available

ThematchAll() method ofString values returns an iterator of all results matching this string against aregular expression, includingcapturing groups.

Try it

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"]

Syntax

js
matchAll(regexp)

Parameters

regexp

A regular expression object, or any object that has aSymbol.matchAll method.

Ifregexp is not aRegExp object and does not have aSymbol.matchAll method, it is implicitly converted to aRegExp by usingnew RegExp(regexp, 'g').

Ifregexpis a regex, then it must have the global (g) flag set, or aTypeError is thrown.

Return value

Aniterable iterator object (which is not restartable) of matches or an empty iterator if no matches are found. Each value yielded by the iterator is an array with the same shape as the return value ofRegExp.prototype.exec().

Exceptions

TypeError

Thrown if theregexpis a regex that does not have the global (g) flag set (itsflags property does not contain"g").

Description

The implementation ofString.prototype.matchAll doesn't do much other than calling theSymbol.matchAll method of the argument with the string as the first parameter (apart from the extra input validation that the regex is global). The actual implementation comes fromRegExp.prototype[Symbol.matchAll]().

Examples

Regexp.prototype.exec() and matchAll()

WithoutmatchAll(), it's possible to use calls toregexp.exec() (and regexes with theg flag) in a loop to obtain all the matches:

js
const regexp = /foo[a-z]*/g;const str = "table football, foosball";let match;while ((match = regexp.exec(str)) !== null) {  console.log(    `Found ${match[0]} start=${match.index} end=${regexp.lastIndex}.`,  );}// Found football start=6 end=14.// Found foosball start=16 end=24.

WithmatchAll() available, you can avoid thewhile loop andexec withg. Instead, you get an iterator to use with the more convenientfor...of,array spreading, orArray.from() constructs:

js
const regexp = /foo[a-z]*/g;const str = "table football, foosball";const matches = str.matchAll(regexp);for (const match of matches) {  console.log(    `Found ${match[0]} start=${match.index} end=${      match.index + match[0].length    }.`,  );}// Found football start=6 end=14.// Found foosball start=16 end=24.// matches iterator is exhausted after the for...of iteration// Call matchAll again to create a new iteratorArray.from(str.matchAll(regexp), (m) => m[0]);// [ "football", "foosball" ]

matchAll will throw an exception if theg flag is missing.

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

matchAll internally makes a clone of theregexp — so, unlikeregexp.exec(),lastIndex does not change as the string is scanned.

js
const regexp = /[a-c]/g;regexp.lastIndex = 1;const str = "abc";Array.from(str.matchAll(regexp), (m) => `${regexp.lastIndex} ${m[0]}`);// [ "1 b", "1 c" ]

However, this means that unlike usingregexp.exec() in a loop, you can't mutatelastIndex to make the regex advance or rewind.

Better access to capturing groups (than String.prototype.match())

Another compelling reason formatchAll is the improved access to capture groups.

Capture groups are ignored when usingmatch() with the globalg flag:

js
const regexp = /t(e)(st(\d?))/g;const str = "test1test2";str.match(regexp); // ['test1', 'test2']

UsingmatchAll, you can access capture groups easily:

js
const 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]

Using matchAll() with a non-RegExp implementing[Symbol.matchAll]()

If an object has aSymbol.matchAll method, it can be used as a custom matcher. The return value ofSymbol.matchAll becomes the return value ofmatchAll().

js
const str = "Hmm, this is interesting.";str.matchAll({  [Symbol.matchAll](str) {    return [["Yes, it's interesting."]];  },}); // returns [["Yes, it's interesting."]]

Specifications

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

Browser compatibility

See also

Help improve MDN

Learn how to contribute.

This page was last modified on byMDN contributors.


[8]ページ先頭

©2009-2025 Movatter.jp