liveBook · Manning

Global regular expression

As explained in Secrets of the JavaScript Ninja, Second Edition

A regular expression with the g flag, enabling successive searches for matches in a string.

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

How Secrets of the JavaScript Ninja, Second Edition covers it

How deep it goes
Compares global and local `match` results and explains stateful repeated `exec` calls, but stops short of using captures within a regex.
Examples
Uses HTML tags to contrast local and global matches and demonstrate capturing during a global search.
What it assumes
Assumes familiarity with regular-expression captures and `String.match` rather than teaching them from zero.
What you can do after
Apply it via `String.match` for a list of matches or repeated `RegExp.exec` calls when captures are needed.
How it connects
Connects regular-expression captures with `String.match` and `RegExp.exec`.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Secrets of the JavaScript Ninja, Second Edition. The section links point to the parts of the book it draws on.