All files title-case.ts

100% Statements 22/22
100% Branches 12/12
100% Functions 1/1
100% Lines 22/22

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        1x                 1x 3x 3x 3x 20x 20x 17x 15x 7x 7x 7x 20x 7x 7x   20x 1x 1x   12x 20x 3x 3x  
/**
 * Regular expression matching common English articles, conjunctions, and prepositions for title casing.
 * @internal
 */
const titles = /^(a|an|and|as|at|but|by|en|for|if|in|nor|of|on|or|per|the|to|vs?\.?|via)$/iu;
 
/**
 * Convert a string to a title, capitalizing each word, except for the small words
 * @param input - the string to make title case
 * @returns the string in title case
 * @group String
 * @category Case Conversion
 */
export function titleCase(input: string): string {
  return input.replaceAll(
    /[A-Za-z0-9\u00C0-\u00FF]+[^\s-]*/gu,
    (match, index: number, word: string) => {
      if (
        index > 0 &&
        index + match.length !== word.length &&
        match.search(titles) > -1 &&
        word.charAt(index - 2) !== ':' &&
        (word.charAt(index + match.length) !== '-' || word.charAt(index - 1) === '-') &&
        word.charAt(index - 1).search(/[^\s-]/u) < 0
      ) {
        return match.toLocaleLowerCase();
      }
 
      if (match.slice(1).search(/[A-Z]|\../u) > -1) {
        return match;
      }
 
      return match.charAt(0).toLocaleUpperCase() + match.slice(1);
    },
  );
}