views:

40

answers:

1

Hello all,

I understand that .match() returns an array of the matches, or null if none are found. But how do I go about accessing the values of capturing groups used with .match?

For example:

var val = whatever.match('(?:^|;) ?' + stuff + '=([^;]*)(?:;|$)');

Assuming the regular expression matches more than once, how do I access the value of the capturing group in a particular match?

Thanks!!

+1  A: 

Use array notation: [0], [1], etc.

var val = whatever.match('(?:^|;) ?' + stuff + '=([^;]*)(?:;|$)');
if(val != null) {
    var first = val[0];
    //...
}
Jacob Relkin
Right, but if the regex matches more than one item, val itself is already an array right? So then val[0] would just return the first match.
Alex
Correct. If the returned value from `match` is non-null, it is an array.
Jacob Relkin