The matchAll()
method returns an iterator of all matched string.
str.matchAll(regexp)
The RegExp object must have the /g flag, otherwise a TypeError will be thrown.
const regexp = RegExp('foo[a-z]*','g'); const str = 'foobar football footware 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}.`); }
matchAll()
will throw an exception if the g flag is missing.
const regexp = RegExp('[a-c]',''); const str = 'abc'; str.matchAll(regexp);/* www . j a v a 2 s . co m*/
Using matchAll()
to access capture groups:
const regexp = RegExp('[a-c]',''); const str = 'abc'; str.matchAll(regexp);/*from w w w .j av a 2 s. com*/ let array = [...str.matchAll(regexp)]; console.log(array[0]); console.log(array[1]);