JS: 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 RegExp Flag global. Then
str.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.
The argument regexObj must have the RegExp Flag global, else it's error.
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.)
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
- JS: RegExp Tutorial
- JS: Regex Functions
- JS: RegExp Syntax
- JS: RegExp Flag
- JS: Regex Replace String Dollar Sign
- JS: Regex Replace Function Args
- JS: RegExp Object
- JS: RegExp Constructor
- JS: RegExp.prototype
- JS: String.prototype.search
- JS: String.prototype.match
- JS: String.prototype.matchAll
- JS: String.prototype.replace
- JS: String.prototype.replaceAll
- JS: RegExp.prototype.test
- JS: RegExp.prototype.exec