liveBook · Manning

Exec method

As explained in Secrets of the JavaScript Ninja, Second Edition

A RegExp method in JavaScript that executes a pattern search and returns the next match result, including captures when available.

When a global search needs both every match and its captures, use RegExp.exec repeatedly. Each call returns the next match and its captures, advancing from the previous call. section 10.4 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.");

The HTML tag example uses a global pattern and repeated exec calls to find six tags, with three captures in each result. section 10.4.2

How Secrets of the JavaScript Ninja, Second Edition covers it

How deep it goes
Explains repeated calls, retained state, and captures per match, but stops short of using captures within regexes.
Examples
Uses an HTML string containing opening and closing tags to demonstrate global matching and captures.
What it assumes
Assumes familiarity with regular-expression patterns, global matching, and capture groups.
What you can do after
Apply JavaScript's RegExp.exec method to iterate global matches and inspect their captures.
How it connects
Links global regular expressions and String.prototype.match through their different handling of matches and captures.

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.