Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to separate country code form Phone number?

Tags:

javascript

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.

like image 786
Joomler Avatar asked Aug 21 '17 12:08

Joomler


People also ask

How do I type my phone number with country code?

When adding international phone numbers, type the + sign, then the country code followed by the local number.

When using +44 do I drop the 0?

It shows that the next two digits "44" are the code for the United Kingdom when phoning from another country. You replace them with the zero when phoning inside the UK.


Video Answer


1 Answers

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>
like image 129
lumio Avatar answered Oct 10 '22 11:10

lumio