Utils/filterText.js

/**
 * Uses regex to recursively filter a string.
 *
 * @function filterText
 * @since 1.0.0
 * @memberof module:Utils
 *
 * @param {string} text - The text you would like to filter
 * @param {regex} regex - The regex pattern to use for filtering
 * @param {function} action - The callback function to evaluate
 *
 * @returns {array} An array of groups that match the evaluation
 * @example
 * import {filterText} from 'fenix-tools'
 *
 * const re = /pattern/g
 * const matches = filterText(text, re, (match) => {
 *  console.log(match) // => The full match group returned from regex
 *  // Perform an evaluation to store specific matches
 * })
 *
 */
export default function filterText (text, regex, action) {
  const result = []
  let match
  const re = regex
  while (match = re.exec(text)) { // eslint-disable-line no-cond-assign
    if (action(match)) {
      result.push(match)
    }
  }
  return result
}