JavaScript: String.prototype.matchAll
New in JS2020.
str.matchAll(findStr)
-
If argument findStr is a string, it is converted to regex regexObj by RegExp with added global flag
g
. thenstr.matchAll(regexObj)
is called. str.matchAll(regexObj)
-
Return a
Iterable Object
(is also an Iterator) of all occurrences and captures, or return
null
if no match.
For each item in result, it is an array with meaning like this:
[matchStr, capture1, capture2, etc]
The first element of each array is occurrence of match. Rest elements are the captures. (Captures are always substring of the occurrence.)
The argument regexObj must have the flag
g
, else it's error. [see RegExp Flags]const ss = "year 2010, 2015, and 2020"; const xx = ss.matchAll(/\d\d(\d)(\d)/g); for (let k of xx) console.log(k); /* [ "2010", "1", "0" ] [ "2015", "1", "5" ] [ "2020", "2", "0" ] The first element of each array is occurrence of match. Rest elements are the captures. captures are always substring of the occurrence. */
If giving a
RegExp Object
as argument, it must have the global flag g
"year 1999".matchAll(/\d{4}/); // error: Uncaught TypeError: String.prototype.matchAll called with a non-global RegExp argument
Verifying Result is Iterable and Iterator
/* check matchAll result is iterable and iterator */ const xx = "year 1999 and 2020".matchAll(/\d/g); console.log( Reflect.has(xx, Symbol.iterator), Reflect.has(xx, "next"), );
JavaScript Regular Expression
- RegExp Tutorial
- RegExp Functions
- RegExp Syntax
- RegExp Flags
- Replacement String Dollar Sign Sequence
- Replacement Function Arguments