Regex matcher function

by Csaba Hellinger

JavaScript

/** 
 * Matches `string` to `regex`. If there's a match, calls `onMatch` with
 * the captured groups passed in individual parameters.
 * @param {RegExp} regex The regex pattern, with capture groups.
 * @param {string} string The string to match.
 * @param {function} onMatch The callback function, with parameter for each group.
 * @returns {undefined}
 */
function regexMatch(regex, string, onMatch = utils.noop) {
    const match = regex.exec(string);
    if (match) {
        onMatch(...match.splice(1));
    }
}

const url = 'home/12?page=1',
	regex = /^(home)\/(\d+)(|\?.*)$/i;

regexMatch(regex, url, (endpoint, id, params) => {
	console.log('endpoint:', endpoint);
    console.log('id:', id);
    console.log('params:', params);
});