liveBook · Manning

Backreference

As explained in Secrets of the JavaScript Ninja, Third Edition

A backreference is a regular-expression construct that matches text previously captured by a capturing group.

How can a regular expression find the same word twice when it does not know the word in advance? A backreference matches text already captured by an earlier parenthesized group. Write a backslash followed by the capture number, starting with \1. section 12.4.3

Match the same character, not just the same kind

The pattern /^([dtn])a\1/ matches a string beginning with dad, tat, or nan: the character after a must equal the one captured before it. By contrast, /^[dtn]a[dtn]/ permits different characters on either side of a. section 12.2.2

Listing 12.7 Using a backreference to identify repetition
const doubledWordRegex = /\b([a-z]+) \1\b/i; #A
const report = "The ninja's heart went doki doki";
const found = report.match(doubledWordRegex);

if (found === null) {
  console.assert(false, "Match expected");
} else {
  const [match, word] = found;
  console.assert(
    match === "doki doki",
    "The full match is the doubled word 'doki doki'",
  );
  console.assert(
    word === "doki",
    "The capture is the word 'doki'",
  );
}

In /\b([a-z]+) \1\b/i, the group captures a word and \1 requires it again after a space. The example matches “doki doki”; the result contains both the full match and the captured word. Word boundaries prevent matching the repetition inside longer words, while i permits uppercase letters. section 12.4.3

The key distinction is between repeating a pattern and repeating its result: a character class can match another eligible character, but a backreference must match what the group captured in this match. section 12.2.2

How Secrets of the JavaScript Ninja, Third Edition covers it

How deep it goes
Defines numbered syntax and works through character and doubled-word matches, without detailing regex-engine internals.
Examples
Uses matching characters around “a” and the repeated phrase “doki doki” to show exact reuse of captured text.
What it assumes
Builds from parenthesized captures and their numbering before introducing references to captured values.
What you can do after
Apply it via JavaScript regular expressions to identify repeated substrings or whole words.
How it connects
Connects capturing groups, character classes, word boundaries, case-insensitive matching, and match results.

Also explained in

Compare how 3 books explain backreference →

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.