Backreference Pattern
Regular Expressions: Backreference Pattern
Regular expressions: Backreferences in pattern: \N and \k<name>
What is backreferencing in regular JavaScript expressions?
View Answer:
Interview Response: When matching string patterns using regular expressions, we might wish to match the same piece of text more than once. When the pattern used to perform the first match includes non-literal elements, we can look for the repeated text using a backreference. A backreference in a regular expression identifies a previously matched group and looks for the exact text again.
Code Example:
// Backreference by number: \N
let str = `He said: "She's the one!" "She's the one!".`;
let regexp = /(['"])(.*?)\1/g;
alert(str.match(regexp)); // "She's the one!"
// Backreference by name: \k<name>
let str = `He said: "She's the one!".`;
let regexp = /(?<quote>['"])(.*?)\k<quote>/g;
alert(str.match(regexp)); // "She's the one!"