When a regular expression finds a match, String.match can return more than a yes-or-no answer: it can give you the matched text and, for a local search, its captures. section 10.4 section 10.4.2
The regex’s global flag changes what the result array contains:
- Without g, match returns the first match and any captures. section 10.4.2
- With g, match returns all matches in the string, but not captures for each match. section 10.4.2
- To search globally while retaining captures, repeatedly call the regex’s exec method; each call advances to the next match. 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 the local and global results when matching HTML tags, including which captures appear. section 10.4.2

