0

If I want to capture e.g. text that is either in round brackets or square brackets and use this regular expression:

\[(.+)\]|\((.+)\)

I get for the example "[test]" the results "test" and "undefined" and for "(test)" the results "undefined" and "test". How can I manage to get only "test" as result?

(This regex is only an example, my actual regex is more complex but with the same problem.)

Jomo
  • 79
  • 8

1 Answers1

0

If the specific group numbers that get captured don't matter, just the text they contain, I think the easiest thing is to just filter the match afterwards to remove the undefined groups:

for (const match of ' [foo] (bar) '.matchAll(/\[(.+)\]|\((.+)\)/g)) {
  const [, text] = match.filter(m => m !== undefined);
  console.log(text);
}
CertainPerformance
  • 313,535
  • 40
  • 245
  • 254