[英]How to separate country code form Phone number?
I was having lots of phone numbers [eg: 1-123-456-7890] in my DB. 我的数据库中有很多电话号码[例如:1-123-456-7890]。 What I have to do is, separate country dialing code [in this case 1 which is for US/Canada] from the phone number.
我要做的是,将电话号码中的国家/地区代码[在本例中为1,用于美国/加拿大]分开。
What I have tried is - I made a json list of all countries and when getting loading the page, I separated phone number and country code. 我尝试过的是-我列出了所有国家/地区的json列表,并在加载页面时将电话号码和国家/地区代码分开。 and it was working fine till I got some numbers which starts with '+' or having only 6 or 7 digits in the phone number(in this case there is no country code).
直到我得到一些以“ +”开头或电话号码中只有6或7位数字的电话(在这种情况下,没有国家/地区代码),它都可以正常工作。
I have tried google's GeoName API but it doesn't return what I was expecting. 我已经尝试过Google的GeoName API,但没有返回我期望的结果。 And i couldn't find any API for getting the country code form the phone number.
而且我找不到用于从电话号码获取国家/地区代码的任何API。
This is one of the sort of problems which is quite complicated. 这是非常复杂的问题之一。 I would suggest to use a library like libphonenumber-js .
我建议使用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>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.