W3docs

Regex backreferences in pattern: \n and \k<name>

Before we get into the details of backreferences, let's first understand regular expressions in JavaScript. They help us find patterns in text. Backreferences

Most of a regular expression matches fixed text, but sometimes you need to match text that has to be identical to something you matched earlier — without knowing in advance what that text is. A backreference solves exactly this. It lets a pattern say "match the same thing the group captured a moment ago."

Classic jobs for backreferences include detecting a doubled word (the the), matching a string wrapped in balanced quotes ("..." or '...' but not "...'), or verifying that an HTML-like tag is closed by the same tag name. None of these are possible with ordinary literal patterns, because the text to match isn't known until the regex runs.

This guide covers numbered backreferences (\1, \2, …), named backreferences (\k<name>), how groups are numbered, the common gotchas, and how to reuse captured text in String.prototype.replace().

How to Use Backreferences

Inside a pattern, a backslash followed by a number refers to the text captured by a capturing group. \1 is whatever group 1 matched, \2 is group 2, and so on. The key point: it matches the captured text, not the group's pattern again.

javascript— editable

Here (\w+) captures a word into group 1, \s matches the space, and \1 requires the same word again. So hello hello matches, but hello world does not — \1 must equal what group 1 captured, not just match \w+ a second time.

How groups are numbered

Group numbers are assigned by the position of each group's opening parenthesis, left to right. This matters when you have multiple or nested groups:

javascript— editable

The whole match is group 0 (m[0]), which is why the first capturing group is \1, not \0. For nested groups, the outer group gets the lower number because its ( comes first.

Using Named Groups

Numbered references get hard to read once a pattern grows. Instead, you can name a group with (?<name>…) and reference it with \k<name>. For more on declaring named groups, see Capturing Groups.

javascript— editable

Here (?<word>\w+) is a named group and \k<word> backreferences it. After a successful match, the captured text is also available on the match.groups object. Named groups and \k<name> work in all modern browsers and current Node.js without any flag.

Reusing Captures in replace()

The most common day-to-day use of backreferences is not inside the pattern — it's in the replacement string of String.prototype.replace(). There you reference captured text with $1, $2, … (or $<name> for named groups).

A neat example collapses an accidentally doubled word down to one:

javascript— editable

Note the distinction: \1 (backslash) is used inside the pattern, while $1 (dollar sign) is used in the replacement string. Mixing them up is a frequent source of bugs.

Gotcha: Non-Participating Groups

A backreference to a group that did not participate in the match behaves specially. If the group never matched (for example, it was inside an unused alternative), its captured value is undefined, and in JavaScript the backreference then matches the empty string — it succeeds without consuming anything.

javascript— editable

This is easy to overlook: you might expect \1 to fail when the group didn't match, but instead it quietly matches nothing. Structure your alternation carefully if you rely on a group always having captured something.

A Genuine Backreference: Balanced Quotes

A practical pattern that requires a backreference is matching a quoted string where the closing quote must be the same character as the opening one — "..." and '...' are valid, but "...' is not.

javascript— editable

The group (['"]) captures whichever quote character opened the string, and \1 forces the close to be that exact character. A plain ["'].*?["'] could not enforce this — it would happily match "...'. This is the difference between a lookahead/lookbehind (which only asserts) and a backreference (which matches the captured text again).

Conclusion

Reach for a backreference whenever a later part of the match must equal text matched earlier — doubled words, balanced quotes, same-name tags, or "adjacent characters must differ" rules. Remember the three essentials:

  • Numbered groups are counted by their opening (, starting at \1; the whole match is group 0.
  • Use \1 / \k<name> inside the pattern, and $1 / $<name> in replace().
  • A non-participating group makes its backreference match the empty string, so guard your alternations.

For the building blocks, review Capturing Groups, Character Classes, and Lookahead and Lookbehind.

Practice

Practice
Which of the following statements about backreferences in JavaScript regular expressions is true?
Which of the following statements about backreferences in JavaScript regular expressions is true?
Was this page helpful?