stringUtils.ts 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. import crypto from 'crypto'
  2. export default class StringUtils {
  3. /**
  4. * Normalise une chaine de caractères en retirant la casse et les caractères spéciaux, à des fins de recherche
  5. * par exemple
  6. * @param s
  7. */
  8. public static normalize(s: string): string {
  9. return s
  10. .toLowerCase()
  11. .replace(/[éèẽëê]/g, 'e')
  12. .replace(/[ç]/g, 'c')
  13. .replace(/[îïĩ]/g, 'i')
  14. .replace(/[àã]/g, 'a')
  15. .replace(/[öôõ]/g, 'o')
  16. .replace(/[ûüũ]/g, 'u')
  17. .replace(/[-]/g, ' ')
  18. .trim()
  19. }
  20. /**
  21. * Convertit le paramètre d'entrée en entier
  22. * A la différence de parseInt, cette méthode accepte aussi les nombres.
  23. * @param s
  24. */
  25. public static parseInt(s: string | number) {
  26. return typeof s === 'number' ? s : parseInt(s)
  27. }
  28. /**
  29. * Hash une chaine de caractères avec l'algorithme demandé
  30. *
  31. * @param input
  32. * @param algorithm
  33. */
  34. public static async hash(input: string, algorithm: string = 'SHA-256') {
  35. const textAsBuffer = new TextEncoder().encode(input)
  36. const isNode =
  37. typeof process !== 'undefined' &&
  38. process.versions != null &&
  39. process.versions.node != null
  40. const cryptoLib = isNode ? crypto : window.crypto
  41. const hashBuffer = await cryptoLib.subtle.digest(algorithm, textAsBuffer)
  42. const hashArray = Array.from(new Uint8Array(hashBuffer))
  43. return hashArray.map((item) => item.toString(16).padStart(2, '0')).join('')
  44. }
  45. }