All files / utils/matchString matchString.js

100% Statements 19/19
100% Branches 18/18
100% Functions 8/8
100% Lines 17/17

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45    33x   54x   78x 61x           54x 54x     59x   59x 2x   57x   59x           54x 1x   1x     53x 122x     77x        
import escapeRegExp from 'lodash/escapeRegExp';
 
const matchString = (match, str, ignoreNull = true, simpleSplit = true) => {
  // Simple regex split -- this is default behaviour
  const regexSimple = new RegExp(
    `${match.split(/(\s+)/)
      .filter(h => h.trim())
      .map(hl => '(' + escapeRegExp(hl) + ')')
      .join('|')}`,
    'gi'
  );
 
  // Split Elvis "The King" Presley into [Elvis, The King, Presley]
  const quotedParts = match.match(/"[^"]*"|\S+/g) || [];
  const regex = new RegExp(
    `${
      quotedParts
        .filter(h => h.trim())
        .map(quotedSection => {
          if (quotedSection.charAt(0) === '"' && quotedSection.charAt(quotedSection.length - 1) === '"') {
            return quotedSection.slice(1, -1);
          }
          return quotedSection;
        })
        .map(hl => '(' + escapeRegExp(hl) + ')')
        .join('|')
    }`,
    'gi'
  );
 
  if (ignoreNull && !match) {
    const nullRegex = /a^/gi; // Should match nothing
 
    return [[str], nullRegex];
  }
 
  if (simpleSplit) {
    return [str.split(regexSimple)?.filter(s => s != null && s !== ''), regexSimple];
  }
 
  return [str.split(regex)?.filter(s => s != null && s !== ''), regex];
};
 
export default matchString;