'JS regexp: exec(): "merge" different groups to the same result

A simplified example: Using this regular expression

/^(?:(a)(b)|(c)(d))$/.exec(value);

results in an array of 5 elements if matching, either

["ab", "a", "b", undefined, undefined]

or

["cd", undefined, undefined, "c", "d"]

Is it possible to change the regular expression in a way to get the following results? Either

["ab", "a", "b"]

or

["cd", "c", "d"]

but still not matching "ad" or "cb"?

(Note that a, b, c, and d should be arbitrary complex regular expressions in reality).



Solution 1:[1]

Yes you can use Array#filter() method:

m = /^(?:(a)(b)|(c)(d))$/.exec('ab').filter(Boolean);
//=> ["ab", "a", "b"]

Solution 2:[2]

var result = /^(a)(b)$/.exec(value) || /^(c)(d)$/.exec(value);

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 vinzee