extractCountryCallingCodeFromInternationalNumberWithoutPlusSign.js 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  1. import Metadata from '../metadata.js';
  2. import matchesEntirely from './matchesEntirely.js';
  3. import extractNationalNumber from './extractNationalNumber.js';
  4. import checkNumberLength from './checkNumberLength.js';
  5. import getCountryCallingCode from '../getCountryCallingCode.js';
  6. /**
  7. * Sometimes some people incorrectly input international phone numbers
  8. * without the leading `+`. This function corrects such input.
  9. * @param {string} number — Phone number digits.
  10. * @param {string?} country
  11. * @param {string?} callingCode
  12. * @param {object} metadata
  13. * @return {object} `{ countryCallingCode: string?, number: string }`.
  14. */
  15. export default function extractCountryCallingCodeFromInternationalNumberWithoutPlusSign(number, country, callingCode, metadata) {
  16. var countryCallingCode = country ? getCountryCallingCode(country, metadata) : callingCode;
  17. if (number.indexOf(countryCallingCode) === 0) {
  18. metadata = new Metadata(metadata);
  19. metadata.selectNumberingPlan(country, callingCode);
  20. var possibleShorterNumber = number.slice(countryCallingCode.length);
  21. var _extractNationalNumbe = extractNationalNumber(possibleShorterNumber, metadata),
  22. possibleShorterNationalNumber = _extractNationalNumbe.nationalNumber;
  23. var _extractNationalNumbe2 = extractNationalNumber(number, metadata),
  24. nationalNumber = _extractNationalNumbe2.nationalNumber; // If the number was not valid before but is valid now,
  25. // or if it was too long before, we consider the number
  26. // with the country calling code stripped to be a better result
  27. // and keep that instead.
  28. // For example, in Germany (+49), `49` is a valid area code,
  29. // so if a number starts with `49`, it could be both a valid
  30. // national German number or an international number without
  31. // a leading `+`.
  32. if (!matchesEntirely(nationalNumber, metadata.nationalNumberPattern()) && matchesEntirely(possibleShorterNationalNumber, metadata.nationalNumberPattern()) || checkNumberLength(nationalNumber, metadata) === 'TOO_LONG') {
  33. return {
  34. countryCallingCode: countryCallingCode,
  35. number: possibleShorterNumber
  36. };
  37. }
  38. }
  39. return {
  40. number: number
  41. };
  42. }
  43. //# sourceMappingURL=extractCountryCallingCodeFromInternationalNumberWithoutPlusSign.js.map