libphonenumber [Js] get country code only

pietro909 picture pietro909 · Nov 30, 2016 · Viewed 9.5k times · Source

I'm using libphonenumber with the npm package.

The problem I have is this one:

// Get an instance of `PhoneNumberUtil`. 
var phoneUtil = require('googlelibphonenumber').PhoneNumberUtil.getInstance();

phoneUtil.parse('+44') // throws exception
phoneUtil.parse('+44234') // gives me an object to work with

I need to be able to parse a number which can be complete or not. In the worst case scenario, it will be just the country code. And in this case, I want to be able to get the country for it.

Is there a way to accomplish it? The API is not very documented and I'm just experimenting with the REPL while looking at the sources.

Answer

catamphetamine picture catamphetamine · Dec 2, 2016

You can't always find out the country given a phone code because, say, USA and Canada both have 1 code.

For incomplete numbers you can try using asYouType and then access the .country property as explained here:

https://github.com/halt-hammerzeit/libphonenumber-js