Marco Prins
Marco Prins

Reputation: 7419

Javascript regex match() returning part (subset) of match

I am using this JavaScript regex:

var e = new RegExp('(, )?wortel')

So my goal is to match either "wortel" OR ", wortel", thus putting the ", " encapsulated in brackets and using a question mark to indicate one or zero occurences.

But when I execute this line of code:

'pus, wortel'.match(e)

I get this output:

Array [ ", wortel", ", " ]

Why is the second result(", ") being included in the matches? Does my regex not require the word "wortel" ? And how do I achieve my desired regex specifications?

PS I am used to Ruby regex, so explaining the difference might help

Upvotes: 1

Views: 291

Answers (1)

anubhava
anubhava

Reputation: 785156

That is because of the optional capturing group in your regex:

var e = new RegExp('(, )?wortel');

You can avoid capturing ", " by using a non capturing group with (?:...) syntax:

var e = new RegExp('(?:, )?wortel');

Here (?:, )? makes it non capturing group.

Now result will be just one element:

Array [ ", wortel" ]

Upvotes: 5

Related Questions