JSFiddle - React, Tailwind, and code Playground

by ravishi

JavaScript

function getRegexMatches(regex, string) {
    if(!(regex instanceof RegExp)) {
        return "ERROR";
    }
    else {
        if (!regex.global) {
            // If global flag not set, create new one.
            var flags = "g";
            if (regex.ignoreCase) flags += "i";
            if (regex.multiline) flags += "m";
            if (regex.sticky) flags += "y";
            regex = RegExp(regex.source, flags);
        }
    }
    var matches = [];
    var match = regex.exec(string);
    while (match) {
        if (match.length > 2) {
            var group_matches = [];
            for (var i = 1; i < match.length; i++) {
                group_matches.push(match[i]);
            }
            matches.push(group_matches);
        }
        else {
            matches.push(match[1]);
        }
        match = regex.exec(string);
    }
    return matches;
}

var matches = getRegexMatches(/(dog)/, "dog boat, cat car dog");
console.log(matches);

var matches = getRegexMatches(/(dog|cat) (boat|car)/, "dog boat, cat car");
console.log(matches);