0

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!

1
  • Try to use the global search Commented Nov 22, 2014 at 17:05

3 Answers 3

3

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
Sign up to request clarification or add additional context in comments.

Comments

1

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"].

1 Comment

Thanks for your brief but awesome solu!
0

Use this

var y = x.match(/(red|green)/gi);

Answer is

y = ["red"]

1 Comment

The question is not about how to match but asking for explanation on capturing group

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.