stripIddPrefix.js 1.1 KB

123456789101112131415161718192021222324252627282930
  1. import Metadata from '../metadata.js'
  2. import { VALID_DIGITS } from '../constants.js'
  3. const CAPTURING_DIGIT_PATTERN = new RegExp('([' + VALID_DIGITS + '])')
  4. export default function stripIddPrefix(number, country, callingCode, metadata) {
  5. if (!country) {
  6. return
  7. }
  8. // Check if the number is IDD-prefixed.
  9. const countryMetadata = new Metadata(metadata)
  10. countryMetadata.selectNumberingPlan(country, callingCode)
  11. const IDDPrefixPattern = new RegExp(countryMetadata.IDDPrefix())
  12. if (number.search(IDDPrefixPattern) !== 0) {
  13. return
  14. }
  15. // Strip IDD prefix.
  16. number = number.slice(number.match(IDDPrefixPattern)[0].length)
  17. // If there're any digits after an IDD prefix,
  18. // then those digits are a country calling code.
  19. // Since no country code starts with a `0`,
  20. // the code below validates that the next digit (if present) is not `0`.
  21. const matchedGroups = number.match(CAPTURING_DIGIT_PATTERN)
  22. if (matchedGroups && matchedGroups[1] != null && matchedGroups[1].length > 0) {
  23. if (matchedGroups[1] === '0') {
  24. return
  25. }
  26. }
  27. return number
  28. }