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


