I’m trying to use a pattern like this in a javascript regexp:
"foo.bar".match(/foo\.(buz|bar)/)
but instead of returning foo.bar as I expect, it returns an array:
["foo.bar", "bar"]
I don’t get it. How do I match foo.bar and foo.buz?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
You are correctly matching “foo.bar” or “foo.buz”, but since you have a grouping (
(...)), the returned array includes more than one item:According to the spec, the result is always an array, and the full matched text will be element 0. Elements 1…N will be the matches (in your case, “bar” or “buz”).
If you want make sure your array is length 1, then you want to put
?:after every(to make it a non-capturing group (See https://developer.mozilla.org/en/JavaScript/Guide/Regular_Expressions, syntax(?:x)):However, this is not necessary, as you can always just reference
result[0]for the full match.Incidentally, the
/goption (see the docs again) will also get rid of the capturing groups from the result array. Because/gexecutes a global search, the elements in the result array are used to display all full matches (and in your case given, there’s just one).