Skip to content Skip to sidebar Skip to footer

Detect Country Code By A Given Phone Number In Javascript

I have an object with all available country codes. and I want to know how I can get the country code by a given phone number and display the corresponding country name. the phone n

Solution 1:

FIRST ANSWER:

Just a quick thought, why not count from the other side.

take the 10 numbers off the back side of the number. What you are left with will be the truncated country code. from your example:

num = "16041234567"; code = num.slice(0, num.length-10); country_name = country_code_object[code];

This code assumes that your object can deal with variable length codes (but you could always buffer the front of the code if you needed to.

BROKEN: China does not use 10 number (cells use 11)

FIX: After looking into country codes more completely I relised they are a prefix tree. This means that for a liner time you can just check character by character

num = "16041234567";
country_code;
i = 1;
while (!country_code || i < num.length) {
    country_code = country_code_obj[num.slice(0, i)];
    i++;
}

The nature of country codes will guarantee that the first code that works will be the correct one. (and we can imagine that this must be true, the phone company doesn't know when you are done typing numbers. They just know when you've reached the end of a valid country code)

Post a Comment for "Detect Country Code By A Given Phone Number In Javascript"