Backreferences: \n and $n

Capturing groups may be accessed not only in the result, but in the replacement string, and in the pattern too.

Group in replacement: $n

When we are using replace method, we can access n-th group in the replacement string using $n.

For instance:

let name = "John Smith";

name = name.replace(/(\w+) (\w+)/i, "$2, $1");
alert( name ); // Smith, John

Here $1 in the replacement string means “substitute the content of the first group here”, and $2 means “substitute the second group here”.

Referencing a group in the replacement string allows us to reuse the existing text during the replacement.

Group in pattern: \n

A group can be referenced in the pattern using \n.

To make things clear let’s consider a task. We need to find a quoted string: either a single-quoted '...' or a double-quoted "..." – both variants need to match.

How to look for them?

We can put two kinds of quotes in the pattern: ['"](.*?)['"]. That finds strings like "..." and '...', but it gives incorrect matches when one quote appears inside another one, like the string "She's the one!":

let str = "He said: \"She's the one!\".";

let reg = /['"](.*?)['"]/g;

// The result is not what we expect
alert( str.match(reg) ); // "She'

As we can see, the pattern found an opening quote ", then the text is consumed lazily till the other quote ', that closes the match.

To make sure that the pattern looks for the closing quote exactly the same as the opening one, let’s make a group of it and use the backreference:

let str = "He said: \"She's the one!\".";

let reg = /(['"])(.*?)\1/g;

alert( str.match(reg) ); // "She's the one!"

Now everything’s correct! The regular expression engine finds the first quote (['"]) and remembers the content of (...), that’s the first capturing group.

Further in the pattern \1 means “find the same text as in the first group”.

Please note:

  • To reference a group inside a replacement string – we use $1, while in the pattern – a backslash \1.
  • If we use ?: in the group, then we can’t reference it. Groups that are excluded from capturing (?:...) are not remembered by the engine.
Tutorial map

Comments

read this before commenting…
  • You're welcome to post additions, questions to the articles and answers to them.
  • To insert a few words of code, use the <code> tag, for several lines – use <pre>, for more than 10 lines – use a sandbox (plnkr, JSBin, codepen…)
  • If you can't understand something in the article – please elaborate.