normalize-string.ts 738 B

12345678910111213141516171819
  1. /**
  2. * Normalizes a string to replace non-alphanumeric and diacritical marks with
  3. * plain equivalents.
  4. * Based on https://stackoverflow.com/a/37511463/772859
  5. */
  6. export function normalizeString(input: string, spaceReplacer = ' '): string {
  7. const multipleSequentialReplacerRegex = new RegExp(`([${spaceReplacer}]){2,}`, 'g');
  8. return (input || '')
  9. .normalize('NFD')
  10. .replace(/[\u00df]/g, 'ss')
  11. .replace(/[\u1e9e]/g, 'SS')
  12. .replace(/[\u0308]/g, 'e')
  13. .replace(/[\u0300-\u036f]/g, '')
  14. .toLowerCase()
  15. .replace(/[!"£$%^&*()+[\]{};:@#~?\\/,|><`¬'=‘’©®™]/g, '')
  16. .replace(/\s+/g, spaceReplacer)
  17. .replace(multipleSequentialReplacerRegex, spaceReplacer);
  18. }