liveBook · Manning

Match method

As explained in Secrets of the JavaScript Ninja, Second Edition

A JavaScript method that searches a string with a regular expression and returns match information.

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

How Secrets of the JavaScript Ninja, Second Edition covers it

How deep it goes
Explains result arrays for local and global searches, including capture behavior, and defers referencing captures within the regex.
Examples
Uses an HTML string to compare matching tags locally and globally, then searches them with exec.
What you can do after
Understand how local and global regular-expression searches differ in returned matches and captures.
How it connects
Connects regular expressions and captures with the exec method for global searches that retain capture results.

Also explained in

Compare how 2 books explain match method →

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.