Joomler
Joomler

Reputation: 2798

How to separate the country code from a phone number?

I was having lots of phone numbers (e.g. 1-123-456-7890) in my DB. What I have to do is, separate the country dialing code (in this case 1 which is for US/Canada) from the phone number.

I tried creating a JSON list of all countries and when loading the page, I separated the phone number and country code. It was working fine till I got some numbers which start with + or having only 6 or 7 digits in the phone number (in which case there is no country code).

I have tried Google's GeoName API but it doesn't return what I was expecting. And I couldn't find any API for getting the country code from the phone number.

Upvotes: 8

Views: 19219

Answers (2)

Gabriel Trettin
Gabriel Trettin

Reputation: 11

You just need to have a list of all countries with codes and then loop it and verify if the number starts with the code.

The problem with the libphonenumber-js is that it verifies the number with and without the country code, then sometimes there are more than one possibility for a number.

If you want to strictly find the code and the code is not omitted go with the code below.

  handleInternationalPhoneNumber(number){
    const possibleDDIs = [];

    allCountriesPhonCodes.forEach((country) => {
      if (number.startsWith(country.code)) {
        possibleDDIs.push(country);
      }
    });

    return possibleDDIs;
  }

Upvotes: 1

lumio
lumio

Reputation: 7575

This is one of the sort of problems which is quite complicated. I would suggest to use a library like libphonenumber-js.

I created a little helper function, that uses the US country code by default:

function getCountryCode( input ) {
  // Set default country code to US if no real country code is specified
  const defaultCountryCode = input.substr( 0, 1 ) !== '+' ? 'US' : null;
  let formatted = new libphonenumber.asYouType( defaultCountryCode ).input( input );
  let countryCode = '';
  let withoutCountryCode = formatted;
  
  if ( defaultCountryCode === 'US' ) {
    countryCode = '+1';
    formatted = '+1 ' + formatted;
  }
  else {
    const parts = formatted.split( ' ' );
    countryCode = parts.length > 1 ? parts.shift() : '';
    withoutCountryCode = parts.join( ' ' );
  }
  
  return {
    formatted,
    withoutCountryCode,
    countryCode,
  }
}

console.log( getCountryCode( '1-123-456-7890' ) );
console.log( getCountryCode( '+12133734' ) );
console.log( getCountryCode( '+49300200100' ) );
console.log( getCountryCode( '621234567' ) );
<script src="https://cdnjs.cloudflare.com/ajax/libs/libphonenumber-js/0.4.27/libphonenumber-js.min.js"></script>

Upvotes: 10

Related Questions