Back to JavaScript
2026-03-196 min read

Named backreference: \k<name> (JavaScript)

Learn Named backreference: \k<name> (JavaScript) step by step with clear examples and exercises.

Why This Matters

In this full guide, we will delve into the intricacies of using named backreferences in JavaScript, a powerful feature that enhances your regular expressions (regex) capabilities. We'll explore real-world scenarios, common mistakes, and practical examples to help you master this essential tool for your JavaScript journey.

Named backreferences are crucial when dealing with complex regex patterns, especially in large codebases or projects involving data validation or parsing. They make your expressions more readable, maintainable, and debuggable by allowing you to refer to specific capturing groups using descriptive names rather than numbers. This feature is particularly useful for developers who work on collaborative projects, as it promotes better code organization and reduces the chances of errors due to misunderstandings about which group a backreference is referring to.

Prerequisites

To fully understand this lesson, you should have a solid grasp of the following topics:

  • JavaScript basics (variables, data types, functions)
  • Regular expressions in JavaScript (syntax and basic usage)
  • Grouping and capturing with parentheses in regex
  • JavaScript's match(), replace(), and destructuring assignment methods

Understanding JavaScript's match() method

The match() method is used to find a match for a regular expression pattern within a string. It returns an array containing the matched substring, along with information about captured groups (if any).

const str = "example.com";
const regex = /(\w+)\.com/; // Matches any word followed by .com
const match = str.match(regex);
console.log(match); // Output: ['example', index: 0, input: 'example.com', groups: undefined]

In this example, the match() method returns an array containing the matched substring ('example') and additional information about the match (index, input, and groups). The groups property is undefined because we didn't use any capturing groups in our regex pattern.

Understanding JavaScript's replace() method

The replace() method is used to replace a specified substring within a string using a regular expression pattern. It takes two arguments: the search pattern and the replacement pattern (which can include backreferences).

const str = "example.com";
const regex = /(\w+)\.com/; // Matches any word followed by .com
const replacement = '$1.org'; // Replaces the first captured group with itself, followed by .org
console.log(str.replace(regex, replacement)); // Output: 'example.org'

In this example, we use the $n syntax to refer to the nth captured group in the replacement pattern. The $1 represents the first captured group ('example'), and we append '.org' to it.

Core Concept

Named backreferences allow you to create custom names for capturing groups within a regular expression pattern. This feature is particularly useful when dealing with complex patterns where multiple captures are involved, as it makes the code more readable and easier to understand. The syntax for named backreferences in JavaScript is simple: you use the \k construct, where `` is a unique identifier of your choice.

Here's an example that demonstrates the usage of named backreferences:

const regex = /(?<firstName>\w+) (?<lastName>\w+)/; // Matches a first name followed by a space and a last name
const str = "John Doe";

const match = str.match(regex);
console.log(match.groups); // Output: { firstName: 'John', lastName: 'Doe' }

In this example, we define a regular expression with two named capturing groups: firstName and lastName. The first group captures one or more word characters (\w+) for the first name, while the second group does the same for the last name. We then use the match() method to find a match in our test string and log the groups object, which contains the named captures.

Named Backreference Syntax

The syntax for using named backreferences in JavaScript is as follows:

  • To create a named capture group, enclose the pattern you want to capture within parentheses and follow it with (?...), where name is your chosen identifier.
  • To refer to a named capture group within the same regex pattern, use the construct \k.
  • To refer to a named capture group in replacement patterns (using replace()), use ${name}.

Worked Example

Let's consider a scenario where you have a string containing email addresses and need to extract the domain names using a regular expression. Here's an example of how you can use named backreferences to achieve this:

const regex = /(?<user>[^@]+)@(?<domain>\b[a-zA-Z]+\.[a-zA-Z]{2,}\b)/; // Matches a user followed by @ and the domain name
const str = "john.doe@example.com";

const match = str.match(regex);
console.log(match.groups); // Output: { user: 'john.doe', domain: 'example.com' }

In this example, we define a regular expression with two named capturing groups: user and domain. The first group captures everything up to the @ symbol ([^@]+), while the second group matches the domain name (\b[a-zA-Z]+\.[a-zA-Z]{2,}\b). We then use the match() method to find a match in our test string and log the groups object.

Common Mistakes

Forgetting to assign the named captures to variables

When using named backreferences in replacement patterns (with replace()), you must assign the captured values to variables if you want to use them later in your code. For example:

const str = "example.com";
const regex = /(?<domain>\b[a-zA-Z]+\.[a-zA-Z]{2,}\b)/;
const match = str.match(regex);
const domain = match.groups.domain; // Assign the captured value to a variable
console.log(domain); // Output: 'example.com'

Incorrectly naming capture groups

Named capturing groups must have valid identifiers, which means they cannot contain spaces or special characters (except underscores). For example, the following names are invalid: my name, my_name!, and my_name-1.

Using named backreferences in a pattern that doesn't require them

Named backreferences can make your regular expressions more readable and maintainable, but they also add complexity to your code. If you have a simple regex pattern that doesn't benefit from named captures, it might be better to stick with unnamed groups (enclosed in parentheses) or even inline comments to explain the purpose of each group.

Practice Questions

  1. Write a regular expression that matches phone numbers in the format (XXX) XXX-XXXX using named backreferences.
const regex = /\((?<areaCode>\d{3})\) (?<firstThree>\d{3})-(?<lastFour>\d{4})/;
  1. You have a string containing IP addresses in the CIDR notation (e.g., 192.168.1.1/24). Write a regular expression that extracts the IP address and netmask using named backreferences.
const regex = /(?<ipAddress>\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})/(?<netmask>[/]\d+)/;
  1. Given the following code snippet, how would you update it to log the username and domain separately when matching email addresses?
const regex = /([\w.-]+)@([\w.-]+)/;
const str = "john.doe@example.com";
console.log(str.match(regex)[1]); // Output: 'john.doe@example.com'

To log the username and domain separately, you can update the code as follows:

const regex = /([\w.-]+)@(?<domain>[\w.-]+)/;
const str = "john.doe@example.com";
const match = str.match(regex);
console.log({ username: match[1], domain: match.groups.domain }); // Output: { username: 'john.doe', domain: 'example.com' }

FAQ

Can I use named backreferences in replacement patterns with replace()?

Yes, you can use named backreferences in replacement patterns using ${name} syntax. For example:

const str = "example.com";
const regex = /(?<domain>\b[a-zA-Z]+\.[a-zA-Z]{2,}\b)/;
console.log(str.replace(regex, `${regex.groups.domain}`)); // Output: 'example.com'

Do named backreferences work across all JavaScript engines and browsers?

Named backreferences are supported by most modern JavaScript engines, including V8 (Chrome, Node.js), SpiderMonkey (Firefox), and Chakra (Edge). However, older or less-common engines may not support this feature.

Can I use named backreferences with lookahead and lookbehind assertions?

Yes, you can use named backreferences within lookahead and lookbehind assertions in JavaScript. For example:

const regex = /(?=.*\b(?<name>[A-Z]\w+)\b)(?<phone>\d{3}-\d{3}-\d{4})/;
const str = "John Smith's phone number is (XXX) XXX-XXXX";
console.log(str.match(regex)); // Output: [ null, 'Smith', 'XXX', 'XXX', 'XXXX' ]

In this example, we have a regular expression with two capturing groups: name and phone. The first group uses a positive lookahead assertion to find the name, while the second group matches the phone number. The named backreference (?...) is used within the lookahead assertion.

Named backreference: \k&lt;name&gt; (JavaScript) | JavaScript | XQA Learn