Home > Software engineering >  Why does JavaScript RegExp match multiple strings when a grouping is used?
Why does JavaScript RegExp match multiple strings when a grouping is used?

Time:01-02

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:

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?

CodePudding user response:

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.

  • Related