Lesson guide
Learning objectives
- Explain the main purpose of Backreferences in pattern: \N and \k in JavaScript.
- Identify the syntax, APIs, or concepts introduced in this lesson.
- Use the examples to predict how JavaScript will behave before you run similar code.
- Connect this topic to nearby lessons in Regular expressions.
Real-world context
This lesson matters when you need to recognize where Backreferences in pattern: \N and \k fits into real JavaScript programs. We can use the contents of capturing groups not only in the result or in the replacement string, but also in the pattern itself.
Key ideas
- Backreferences in pattern: \N and \k is part of the Regular expressions chapter, so it builds on the surrounding concepts rather than standing alone.
- Read each code example in two passes: first for the result, then for the rule that explains the result.
- When a section compares similar features, focus on the condition that makes you choose one feature over another.
Key terms
- Backreferences in pattern: \N and \k
- Backreferences
- pattern
- \k
- Regular expressions
We can use the contents of capturing groups (...) not only in the result or in the replacement string, but also in the pattern itself.
Backreference by number: \N
A group can be referenced in the pattern using \N, where N is the group number.
To make clear why that’s helpful, let’s consider a task.
We need to find quoted strings: either single-quoted '...' or a double-quoted "..." – both variants should match.
How to find them?
We can put both kinds of quotes in the square brackets: ['"](.*?)['"], but it would find strings with mixed quotes, like "...' and '...". That would lead to incorrect matches when one quote appears inside other ones, like in the string "She's the one!":
let str = `He said: "She's the one!".`; let regexp = /['"](.*?)['"]/g; alert( str.match(regexp) );
As we can see, the pattern found an opening quote ", then the text is consumed 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, we can wrap it into a capturing group and backreference it: (['"])(.*?)\1.
Here’s the correct code:
let str = `He said: "She's the one!".`; let regexp = /(['"])(.*?)\1/g; alert( str.match(regexp) ); // "She's the one!"
Now it works! The regular expression engine finds the first quote (['"]) and memorizes its content. That’s the first capturing group.
Further in the pattern \1 means “find the same text as in the first group”, exactly the same quote in our case.
Similar to that, \2 would mean the contents of the second group, \3 – the 3rd group, and so on.
Please note:
If we use ?: in the group, then we can’t reference it. Groups that are excluded from capturing (?:...) are not memorized by the engine.
Don’t mess up: in the pattern \1, in the replacement: $1
In the replacement string we use a dollar sign: $1, while in the pattern – a backslash \1.
Backreference by name: \k<name>
If a regexp has many parentheses, it’s convenient to give them names.
To reference a named group we can use \k<name>.
In the example below the group with quotes is named ?<quote>, so the backreference is \k<quote>:
let str = `He said: "She's the one!".`; let regexp = /(?<quote>['"])(.*?)\k<quote>/g; alert( str.match(regexp) ); // "She's the one!"
Common mistakes
- Skipping the small examples and then missing the exact rule that Backreferences in pattern: \N and \k depends on.
- Copying code without changing one value at a time to see which part controls the result.
- Treating similar-looking syntax or APIs as interchangeable before checking their edge cases.
Summary
- Backreferences in pattern: \N and \k gives you one more piece of the JavaScript mental model.
- The examples in this lesson are the quickest way to check whether the rule is clear.
- Revisit the key terms when you meet the same idea in later chapters.
Predict
Before running this backreferences block, predict the five output lines. It compares a loose quote set with numbered and named backreferences, then contrasts pattern backreferences with replacement references.
Reveal explanation
The loose pattern accepts either quote as the closer, so it stops at the apostrophe inside "She's". \1 means “repeat exactly what group 1 matched”, so the closing quote must be the same kind as the opening quote. \k<quote> does the same with a named group. Inside the pattern the syntax is backslash-based (\1); inside the replacement string it is dollar-based ($1, $2).
Try it
Change "bye bye" to "bye Bye" and predict same-word. Then add the i flag and decide whether a backreference also becomes case-insensitive.
Practice
- Rewrite one example from this lesson without looking at the original, then run it and compare the result.
- Change one input, operator, method call, or option in a code sample and predict what will happen before running it.
- Explain Backreferences in pattern: \N and \k in your own words as if you were reviewing it with another learner.
Keep learning
Continue with Alternation (OR) | when you are ready for the next lesson.