How to return only captured groups in a JavaScript RegEx with multiple matches

Simplified example:

/not(?:this|that)(.*?)end/ig.exec('notthis123end notthat45end')


["notthis123end", "123"]

I’m shooting for

["123", "45"]

All I’ve figured out is putting the RE in a RegExp object and running a while loop around the exec, which seems kinda silly, or using match, but getting back the entire match, not just the captured part.

Your RegEx seems to be working fine. Problem is with the interpretation of the output.

  1. To get multiple matches of the RegEx, you should do, something like this

    var regEx = /not(?:this|that)(.*?)end/ig;
    var data  = "notthis123end notthat45end";
    var match = regEx.exec(data);
    while(match !== null) {
        match = regEx.exec(data);

    Note: It is important to store the RegEx in a variable like this and use a loop with that. Because, to get the multiple matches, JavaScript RegEx implementation, stores the current index of the match in the RegEx object itself. So, next time exec is called it picks up from where it left of. If we use RegEx literal as it is, then we ll end up in infinite loop, as it will start from the beginning always.

  2. The result of exec method has to be interpreted like this, the first value is the entire match and the next element onwards we get the groups inside the matches. In this RegEx, we have only one group. So, we access that with match[1].

The answers/resolutions are collected from stackoverflow, are licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0 .
Read More:   (Protractor) Checking whether an input is disabled on click?

Similar Posts