stringUtils.ts 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344
  1. /**
  2. * String utility functions
  3. */
  4. import { type CountryCode, parsePhoneNumberWithError } from 'libphonenumber-js'
  5. /**
  6. * Convert a string to a slug format
  7. * Removes special characters, replaces spaces with hyphens, and converts to lowercase
  8. *
  9. * @param text The text to convert to slug format
  10. * @returns The slugified text
  11. */
  12. export function slugify(text: string): string {
  13. return text
  14. .toString()
  15. .normalize('NFD') // Split accented characters
  16. .replace(/[\u0300-\u036F]/g, '') // Remove diacritics
  17. .toLowerCase()
  18. .trim()
  19. .replace(/\s+/g, '-') // Replace spaces with -
  20. .replace(/[^\w-]+/g, '') // Remove all non-word chars
  21. .replace(/--+/g, '-') // Replace multiple - with single -
  22. .replace(/^-+/, '') // Trim - from start of text
  23. .replace(/-+$/, '') // Trim - from end of text
  24. .substring(0, 30) // Limit to 30 characters
  25. }
  26. // Function to convert phone number to international format
  27. export function convertPhoneNumberToInternationalFormat(
  28. phone: string,
  29. countryCode: CountryCode = 'FR'
  30. ): string {
  31. try {
  32. // Use the provided country code or default to FR
  33. const phoneNumber = parsePhoneNumberWithError(phone, countryCode)
  34. if (phoneNumber && phoneNumber.isValid()) {
  35. return phoneNumber.format('E.164') // format: +33123456789
  36. }
  37. return phone
  38. } catch (error) {
  39. console.error('Error converting phone number:', error)
  40. return phone
  41. }
  42. }