Named Backreferences
What you'll learn: How to reference named capture groups within your regex patterns using a more readable syntax than numbered backreferences.
The Core Idea
In the previous lesson, you learned about named capture groups using (?<name>...). Now you'll see how to reference those named groups within the same pattern using named backreferences with the syntax \k<name>.
While numbered backreferences (like \1, \2) work fine, they become hard to read and maintain in complex patterns. Named backreferences make your regex self-documenting by using descriptive names instead of numbers.
How It Works
The syntax is straightforward: \k<name> where name matches the name you gave your capture group. This tells the regex engine "match exactly what was captured by the group with this name."
// Match repeated words using named backreference
const pattern = /(?<word>\b\w+\b)\s+\k<word>/;
console.log(pattern.test("hello hello")); // true
console.log(pattern.test("hello world")); // false
// Find duplicate tags
const htmlPattern = /<(?<tag>\w+)>.*?<\/\k<tag>>/;
console.log(htmlPattern.test("<div></div>")); // true
console.log(htmlPattern.test("<div></span>")); // false
Why Use Named Backreferences?
Compare these two patterns that do the same thing:
// With numbers - what does \1 refer to?
/(\w+)-(\w+)-\1/
// With names - crystal clear!
/(?<first>\w+)-(?<second>\w+)-\k<first>/
The named version immediately tells you that the third segment must match the first one, not the second.
Key Takeaway: Use \k<name> to create named backreferences that match whatever a named capture group captured, making your regex patterns more readable and maintainable than numbered alternatives.