Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Why does JavaScript RegExp match multiple strings when a grouping is used?

I am currently studying JS and playing around with RegExp API.

I have the following code:

let z = 'somethingsomething';
let matcher_z = /(something)something/;
let another_matcher = /somethingsomething/;

let result = matcher_z.exec(z);
let result1 = another_matcher.exec(z);

console.log(result);
console.log(result1);

The result that I get printed is as follows:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Array [ "somethingsomething", "something" ]
Array [ "somethingsomething" ]

Can someone explain why does a grouping cause the RegExp to match "something", and how can this be mitigated (so that a grouping causes only "somethingsomething" to be matched?

>Solution :

The parens create a capture group, so the results include the captured matches.

This is by design and part of the RegExp exec API:

The returned array has the matched text as the first item, and then one item for each parenthetical capture group of the matched text.

If you don’t want it in the results, don’t capture it.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading