Oliver84
Oliver84

Reputation: 307

Returning the first captured group in each match of a regex in javascript?

I'm trying to use a regex in javascript that will find a section in a string that contains 3 different words. This is the expression that I have so far:

regEx = str.match(/(?=(\b(word1|word2|word3)\b(.+?)\b(word1|word2|word3)\b(.+?)\b(word1|word2|word3)\b))/gi);

This returns 6 empty matches. However, I know that it's matching the words because when I use .exec I can get all the groups in the first match. But how can I get it to return the first group in each match?

Upvotes: 1

Views: 52

Answers (1)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 626748

You can use the following code to get the first submatch in each match:

var re = /(?=(\b(word1|word2|word3)\b(.+?)\b(word1|word2|word3)\b(.+?)\b(word1|word2|word3)\b))/gi;  
var str = 'gg word1 something word2 some word3 ggg';
var res= [];                           // Array for the results
 
while ((m = re.exec(str)) !== null) {  // Loop through matches
    if (m.index === re.lastIndex) {    //  if we have a zero-length match
        re.lastIndex++;                // advance the regex index manually
    }
    res.push(m[1]);                    // Add a value to the resulting array
}
document.body.innerHTML = JSON.stringify(res, 0, 4);

Upvotes: 1

Related Questions