liveBook · Manning

Match method

As explained in Secrets of the JavaScript Ninja, Third Edition

String.prototype.match is a JavaScript String method that retrieves the result of matching a string against a regular expression.

`match()` runs a regular expression against a string and returns matching text, rather than just a yes-or-no result. The shape of its result depends on whether the expression is global. section 12.3 section 12.4.2

Choose what to do with the result based on the expression:

  • Without the `g` flag, `match()` returns an array containing the full match and any captured groups. For example, matching `/\d+/` against `"It's over 9000!"` puts `"9000"` at index 0. section 12.4.2 section 12.3
  • With the `g` flag, `match()` returns an array of full matches; captured groups are not included. Use `matchAll()` when you need captures from each global match, or when you want to process results as an iterator. section 12.4.2

Extracting a number

Run `"It's over 9000!".match(/\d+/)` and check `found?.[0] === "9000"` to confirm the matched text. section 12.3

Listing 12.6 Finding multiple matches with a global regex
const ninjaRoster =
  "Hattori of Iga, Yoshi of Koga, Fuma of Hojo";
const titleRegex = /([^\s,]+) of ([^\s,]+)/g; #A

for (const found of ninjaRoster.matchAll( #B
  titleRegex, #B
)) { #B
  const [, name, clan] = found; #C
  console.log(
    `${name} hails from the ${clan} clan`,
  );
}

See a global-regex example that uses `matchAll()` to extract names and clans from each match. section 12.4.2

How Secrets of the JavaScript Ninja, Third Edition covers it

How deep it goes
Explains result arrays for local and global regexes, including when captures are omitted and matchAll is useful.
Examples
Uses a digit pattern to extract 9000 and a global pattern to extract names and clans.
What you can do after
Apply `match()` to retrieve full matches and captures, and choose `matchAll()` when global captures are needed.
How it connects
Connects regular expressions, capture groups, global matching, and matchAll.

Also explained in

Compare how 3 books explain match method →

Related concepts

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