JavaScript Regex Global Match Groups

To do this with a regex, you will need to iterate over it with .exec() in order to get multiple matched groups. The g flag with match will only return multiple whole matches, not multiple sub-matches like you wanted. Here’s a way to do it with .exec().

var input = "'Warehouse','Local Release','Local Release DA'";
var regex = /'(.*?)'/g;

var matches, output = [];
while (matches = regex.exec(input)) {
    output.push(matches[1]);
}
// result is in output here

Working demo: http://jsfiddle.net/jfriend00/VSczR/


With certain assumptions about what’s in the strings, you could also just use this:

var input = "'Warehouse','Local Release','Local Release DA'";
var output = input.replace(/^'|'$/, "").split("','");

Working demo: http://jsfiddle.net/jfriend00/MFNm3/


Note: With modern Javascript engines as of 2021, you can use str.matchAll(regex) and get all matches in one function call.

Leave a Comment