> For the complete documentation index, see [llms.txt](https://choubey.gitbook.io/javascript-interview-questions/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://choubey.gitbook.io/javascript-interview-questions/question-4.md).

# Question 4

### Question

Can you explain how to use named capture groups and how to access them in JavaScript?

### Answer

Named capture groups add clarity and organization to regular expressions by giving meaningful names to the parts of a string you want to extract.

**How They Work:**

1. **Defining Named Groups:** Use parentheses `()` around the capturing group and name it with a valid identifier (letters, numbers, underscores) preceded by a question mark `?`:

   ```javascript
   /(?<name>\w+)\s+(?<age>\d+)/
   ```
2. **Accessing Captures:** After using `exec()`, you can access the captured groups using their names:

   ```javascript
   const regex = /(?<name>\w+)\s+(?<age>\d+)/;
   const match = regex.exec("John 30");
   if (match) {
     console.log(match.groups.name); // Output: "John"
     console.log(match.groups.age);   // Output: "30"
   }
   ```

**Example:**

```javascript
const emailRegex = /(?<username>\w+)\@(?<domain>\w+\.\w+)/;
const email = "john.doe@example.com";

const match = emailRegex.exec(email);

if (match) {
  console.log("Username:", match.groups.username); // Output: Username: john.doe
  console.log("Domain:", match.groups.domain);   // Output: Domain: example.com
}
```

**Key Advantages:**

* **Readability:** Named groups make your regex patterns much easier to understand and maintain.
* **Organization:** They clearly label the parts of a string you're capturing, improving code clarity.
