Josh Weinstein
Josh Weinstein

Reputation: 2968

Is there a specific method for retrieving groups in JavaScript RegEx matches?

So lets say I have this string in JavaScript:

var candidates = "hillary clinton sanders clinton bush"

And then I use this RegEx match and get my matching groups within this array:

candidates.match(/clinton ([a-z]+) ([a-z]+)/)
=> [
    'clinton sanders clinton',
    'sanders',
    'clinton',
    index: 8,
    input: 'hillary clinton sanders clinton bush'
]

Is there any method or way of retrieving just the matching groups? Without having to know exactly how many there are? In python, I accomplish this by doing:

import re
test = "rowing"
temp = re.compile(r"([a-z]+)ing")
temp.match(test).groups()
---> "row"

Upvotes: 0

Views: 44

Answers (1)

sergeyz
sergeyz

Reputation: 1337

The way match works in js, when you have groups in regex, is it will always have the full match at index 0 and the rest of the array will contain groups. So you can just do something like var match = candidates.match(/clinton ([a-z]+) ([a-z]+)/); if (match) match = match.slice(1, match.length);

match will only contain groups. You can put this logic in a function.

Upvotes: 1

Related Questions