What is the method to access captured groups in a JavaScript regular expression

0 votes
With the help of code, can you tell me what the method is to access captured groups in a regular JavaScript expression?
Feb 10 in Java-Script by Ashutosh
• 20,870 points
98 views

1 answer to this question.

0 votes

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

}

answered Feb 10 by Navya

Related Questions In Java-Script

0 votes
1 answer

What are the methods to clear all elements in a JavaScript array?

In JavaScript, there are several methods to ...READ MORE

answered Jan 10 in Java-Script by Navya
170 views
0 votes
1 answer
0 votes
1 answer
0 votes
1 answer

How to create custom pagination in JavaScript?

It enhances user experience by dividing large ...READ MORE

answered Dec 24, 2024 in Java-Script by Navya
108 views
0 votes
1 answer

How do you access the matched groups in a JavaScript regular expression?

Hello, Here’s a method you can use to ...READ MORE

answered May 28, 2020 in Java-Script by Niroj
• 82,840 points
2,072 views
0 votes
1 answer

How to add tooltip to div in react?

You can utilize React's state management to ...READ MORE

answered Dec 24, 2024 in Node-js by Navya
77 views
0 votes
1 answer

Do i need to close connection of mongodb?

Yes, it's important to manage MongoDB connections ...READ MORE

answered Dec 31, 2024 in PHP by Navya
104 views
0 votes
1 answer
0 votes
1 answer

What is the method to check if a JavaScript object is empty?

You can use several methods: 1. Using Object.keys() const ...READ MORE

answered Feb 7 in Java-Script by Navya
94 views
webinar REGISTER FOR FREE WEBINAR X
REGISTER NOW
webinar_success Thank you for registering Join Edureka Meetup community for 100+ Free Webinars each month JOIN MEETUP GROUP