JavaScript: String.prototype.matchAll
New in JS2020.
str.matchAll(regexObj_or_Str)
-
Returns a
Iterable
(is also an Iterator) of all occurrences and captures, or
null
if no match.
For each item in result, it is an array with meaning like this:[substring, capture1, capture2, etc]
- If argument is a regex object, it must have the flag
g
, else it's error. [see RegExp Flags] - If argument is a string, it is converted to regex first by RegExp with added global flag
g
.
- If argument is a regex object, it must have the flag
Example: Get Occurrences with Capture
const txt = "year 1999, 2010, and 2020"; const result = txt.matchAll(/\d{2}(\d{2})/g); for (let k of result) { console.log(k); }; // [ "1999", "99" ] â 1st occurence, and its captures // [ "2010", "10" ] â 2nd occurence, and its captures // [ "2020", "20" ] â 3rd occurence, and its captures
const txt = "year 1999, 2010, and 2020"; const result = txt.matchAll(/\d{2}(\d{2})/g); // to array const arrayResult = [...result]; console.log(arrayResult[0]); // [ "1999", "99" ] console.log(arrayResult[1]); // [ "2010", "10" ] console.log(arrayResult[2]); // [ "2020", "20" ]
Example: Get Occurrences, No Captures
// get all occurrences of year const txt = "year 1999 and 2020"; const result = txt.matchAll(/\d{4}/g); // to array const arrayResult = [...result] console.log(arrayResult); // [ [ "1999" ], [ "2020" ] ]
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
Showing Iterable and Iterator
const txt = "year 1999 and 2020"; const result = txt.matchAll(/\d{4}/g); // result is a iterable console.log(Reflect.has(result, Symbol.iterator)); // true // result is a iterator console.log(Reflect.has(result, "next")); // true