Reputation: 145
I am a newbie to JS RegExp. I got confused by the following RegExp matches.
var x = "red apple"
var y = x.match(/red|green/i)
Now y
is ["red"]
.
However if I add a pair of parentheses around red
and green
and make y to be
var y = x.match(/(red|green)/i)
Now, y
would become ["red", "red"]
. I have searched online https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/RegExp
and found that it's something called
capturing parentheses.
It says For example, /(foo)/ matches and remembers 'foo' in "foo bar." The matched substring can be recalled from the resulting array's elements [1], ..., [n] or from the predefined RegExp object's properties $1, ..., $9.
But I don't understand what does it mean by recalled from the resulting array's element or from predefined RegExp object's properties
? Can anyone please explain ? Thank you!
Upvotes: 0
Views: 261
Reputation: 70722
It means that the match result (obtained from the capturing group) can be accessed by referring to that specific group number [1]
.. [n]
where n
represents the number of the capturing group you want to access.
Note: [0]
applies to the overall match result.
var r = 'red apple'.match(/(red|green) apple/i);
if (r)
console.log(r[0]); //=> "red apple" # entire overall match
console.log(r[1]); //=> "red" # match result from 1st capture group
Upvotes: 3
Reputation: 338148
When the match result is stored to (in this case) y
, y[0]
is always the overall match, while y[1]
.. y[9]
contain the individual capturing groups.
In /(red|green) apple/
, applied to "This is a red apple."
, y
will be ["red apple", "red"]
.
Upvotes: 1