如何将国家/地区代码与电话号码分开?

Joo*_*ler 8 javascript

我的数据库中有很多电话号码(例如 1-123-456-7890)。我要做的是将国家/地区拨号代码(在本例中为美国/加拿大的 1)与电话号码分开。

我尝试创建所有国家/地区的 JSON 列表,并在加载页面时将电话号码和国家/地区代码分开。它工作正常,直到我收到一些以电话号码开头+或只有 6 或 7 位数字的号码(在这种情况下没有国家/地区代码)。

我尝试过 Google 的 GeoName API,但它没有返回我所期望的结果。我找不到任何用于从电话号码获取国家/地区代码的 API。

lum*_*mio 10

这是相当复杂的问题之一。我建议使用像libphonenumber-js这样的库这样的库。

我创建了一个小辅助函数,默认情况下使用美国国家/地区代码:

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' ) );
Run Code Online (Sandbox Code Playgroud)
<script src="https://cdnjs.cloudflare.com/ajax/libs/libphonenumber-js/0.4.27/libphonenumber-js.min.js"></script>
Run Code Online (Sandbox Code Playgroud)