A regular expression with the `g` flag searches for all matches in a string. With `String.match`, the returned array contains the matches, but not captures within each match. section 10.4.2
Need captures as well as a global search? Repeatedly call the regular expression’s `exec` method. It retains state between calls, advancing to the next match and returning that match’s captures. section 10.4.2
Listing 10.5. Differences between global and local searches with match
const html = "<div class='test'><b>Hello</b> <i>world!</i></div>"; const results = html.match(/<(\/?)(\w+)([^>]*?)>/); #A assert(results[0] === "<div class='test'>", "The entire match."); assert(results[1] === "", "The (missing) slash."); assert(results[2] === "div", "The tag name."); assert(results[3] === " class='test'", "The attributes."); const all = html.match(/<(\/?)(\w+)([^>]*?)>/g); #B assert(all[0] === "<div class='test'>", "Opening div tag."); assert(all[1] === "<b>", "Opening b tag."); assert(all[2] === "</b>", "Closing b tag."); assert(all[3] === "<i>", "Opening i tag."); assert(all[4] === "</i>", "Closing i tag."); assert(all[5] === "</div>", "Closing div tag.");
Compare how `match` returns captures for a local search but only matched strings for a global one. section 10.4.2
Listing 10.6. Using the exec method to do both capturing and a global search
const html = "<div class='test'><b>Hello</b> <i>world!</i></div>";
const tag = /<(\/?)(\w+)([^>]*?)>/g;
let match, num = 0;
while ((match = tag.exec(html)) !== null) { #A
assert(match.length === 4,
"Every match finds each tag and 3 captures.");
num++;
}
assert(num === 6, "3 opening and 3 closing tags found.");
See a repeated `exec` loop capture each HTML tag while searching globally. section 10.4.2
