Design & Download
Your JS Library
in Seconds!!!

Snippet: matchAll() - Get All Matching Substrings

Written by Christopher West (cwest) on December 05, 2015.
Gets all of the matches found when matching a regular expression against a string.
function matchAll(str, rgx, opt_fnMapper) {
  var arr, extras, matches = [];
  str.replace(rgx = rgx.global ? rgx : new RegExp(rgx.source, (rgx + '').replace(/[\s\S]+\//g , 'g')), function() {
    arr = slice(arguments);
    extras = arr.splice(-2);
    arr.index = extras[0];
    arr.input = extras[1];
    arr.source = rgx;
    matches.push(opt_fnMapper ? opt_fnMapper.apply(arr, arr) : arr);
  });
  return arr ? matches : null;
}

matchAll(...) API Documentation

Description

Gets all of the matches found when matching a regular expression against a string.

Parameters

  1. str {string}:
    The string to match the regular expression against.
  2. rgx {RegExp}:
    The regular expression to match against str. This regular expression will be matched after if the global flag was set.
  3. opt_fnMapper {Function}:
    Optional. If provided, this function will receive each match and the return value will be appended to the array which will be returned by matchAll(). The arguments will directly correspond to the parenthesized capture groups. The this object will be an array of the arguments passed to the function. The this object will additionally have an index value indicating where the match starts, an input value which is a copy of str, and a source value which is the regular expression used to get all of the matches.

Returns

If the regular expression matched at least once, an array of all of the matches will be returned. Each match will at least have match[0], match.index, match.source and match.input. If capture groups were specified in the regular expression, each will be found in its corresponding index starting with match[1]. If no matches were found, null is returned.