ou can access captured groups from a regular expression match using several methods:
Using String.prototype.match():
The match() method retrieves the result of matching a string against a regular expression. Without the global (g) flag, it returns an array similar to exec().
Example:
const regex = /(\w+) (\w+)/;
const str = 'John Doe';
const result = str.match(regex);
console.log(result[0]); // 'John Doe' (full match)
console.log(result[1]); // 'John' (first captured group)
console.log(result[2]); // 'Doe' (second captured group)
Using String.prototype.matchAll():
The matchAll() method returns an iterator of all results matching a string against a regular expression, including capturing groups. This is particularly useful when using the global (g) flag.
Example:
const regex = /(\w+) (\w+)/g;
const str = 'John Doe Jane Smith';
const matches = str.matchAll(regex);
for (const match of matches) {
console.log(match[0]); // Full match
console.log(match[1]); // First captured group
console.log(match[2]); // Second captured group
}