The matchAll()
function matches a string against a regular expression and returns an iterator of all the matched groups.
str.matchAll(regexp)
RegExp
/g
flag. Otherwise, a TypeError
will be thrown.new Regexp(value)
.Return value
matchAll()
returns an iterator that has an array for each match. In that array, we have:
const regex = /J(ava)([a-z]*)/gi;let str = "Java JavaScript";let allMatchItr = str.matchAll(regex);for(match of allMatchItr) {console.log("\n-----match-----\n");console.log(match);}
In the code above, we have two matches for the RegExp /J(ava)([a-z]*)/gi
; so, the matchAll() method returns an iterator with two array values. In each array:
const regex = /J(?<group_name_1>ava)(?<group_name_2>[a-z]*)/gi;let str = "Java JavaScript";let allMatchItr = str.matchAll(regex);for(match of allMatchItr) {console.log("\n-------Match-------\n");console.log("Matched String =>", match[0]);console.log("Matched value of group_name_1 => ", match.groups['group_name_1']);console.log("Matched value of group_name_2 => ", match.groups['group_name_2']);}
In the above code, we printed the matched string, which is present at the 0th
index of the array. We named the captured group as group_name_1
and group_name_2
in the regex. Each array present in the returned iterator contains the group’s property with the group names as the keys and the matched strings as the values.