formatNationalNumberUsingFormat.js 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  1. import applyInternationalSeparatorStyle from './applyInternationalSeparatorStyle.js'
  2. // This was originally set to $1 but there are some countries for which the
  3. // first group is not used in the national pattern (e.g. Argentina) so the $1
  4. // group does not match correctly. Therefore, we use `\d`, so that the first
  5. // group actually used in the pattern will be matched.
  6. export const FIRST_GROUP_PATTERN = /(\$\d)/
  7. export default function formatNationalNumberUsingFormat(
  8. number,
  9. format,
  10. {
  11. useInternationalFormat,
  12. withNationalPrefix,
  13. carrierCode,
  14. metadata
  15. }
  16. ) {
  17. const formattedNumber = number.replace(
  18. new RegExp(format.pattern()),
  19. useInternationalFormat
  20. ? format.internationalFormat()
  21. : (
  22. // This library doesn't use `domestic_carrier_code_formatting_rule`,
  23. // because that one is only used when formatting phone numbers
  24. // for dialing from a mobile phone, and this is not a dialing library.
  25. // carrierCode && format.domesticCarrierCodeFormattingRule()
  26. // // First, replace the $CC in the formatting rule with the desired carrier code.
  27. // // Then, replace the $FG in the formatting rule with the first group
  28. // // and the carrier code combined in the appropriate way.
  29. // ? format.format().replace(FIRST_GROUP_PATTERN, format.domesticCarrierCodeFormattingRule().replace('$CC', carrierCode))
  30. // : (
  31. // withNationalPrefix && format.nationalPrefixFormattingRule()
  32. // ? format.format().replace(FIRST_GROUP_PATTERN, format.nationalPrefixFormattingRule())
  33. // : format.format()
  34. // )
  35. withNationalPrefix && format.nationalPrefixFormattingRule()
  36. ? format.format().replace(FIRST_GROUP_PATTERN, format.nationalPrefixFormattingRule())
  37. : format.format()
  38. )
  39. )
  40. if (useInternationalFormat) {
  41. return applyInternationalSeparatorStyle(formattedNumber)
  42. }
  43. return formattedNumber
  44. }