liveBook · Manning

Backreference

As explained in Secrets of the JavaScript Ninja, Second Edition

A reference that reuses text previously matched by a capturing group.

A backreference makes a later part of a regular expression match the text captured earlier—not just any text from the same character set. Write it as a backslash followed by the capture number, such as \1. section 10.2.2

Match the same character twice

In /^([dtn])a\1/, the first character is captured; after the a, \1 requires that exact character again. For example, the pattern matches "dad" and "tat", but not "dat". section 10.2.2

/<(\w+)>(.+)<\/\1>/

This pattern captures an opening tag name with (\w+), then uses \1 to require the closing tag to repeat it. It matches simple elements such as <strong>whatever</strong>; it does not establish support for nested markup. section 10.2.2

How Secrets of the JavaScript Ninja, Second Edition covers it

How deep it goes
Defines numbered capture references and illustrates evaluation-time matching, while deferring fuller capture treatment.
Examples
Uses repeated d/t/n characters, simple markup tags, and numbered-digit matching exercises.
What it assumes
Assumes familiarity with regex terms and parenthesized groups, and briefly defines captures as successfully matched portions.
What you can do after
Apply a numbered backreference in a regex to require later text to repeat an earlier capture.
How it connects
Connects backreferences to capturing groups and regular-expression matching.

Also explained in

Compare how 2 books explain backreference →

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.