awesome-phonenumber API完全指南:开发者必知的方法与参数
【免费下载链接】awesome-phonenumberGoogle's libphonenumber pre-compiled with the closure compiler项目地址: https://gitcode.com/gh_mirrors/aw/awesome-phonenumber
awesome-phonenumber是基于Google libphonenumber预编译的电话号码处理工具,提供简单高效的API帮助开发者验证、解析和格式化全球电话号码。本文将系统介绍其核心API方法、参数说明及使用示例,帮助开发者快速掌握这个强大工具的使用技巧。
核心API概览
awesome-phonenumber提供了一系列直观易用的API方法,涵盖电话号码处理的主要场景:
号码解析与验证
parsePhoneNumber
最核心的号码解析函数,支持多种输入格式和地区提示。
参数说明:
phoneNumber(string):待解析的电话号码字符串options(object):可选配置对象,包含:regionCode(string):地区代码(如"US"、"CN"),用于未知国际格式号码的解析
返回值:PhoneNumber对象,包含号码的各种属性和格式化形式
使用示例:
const phone = parsePhoneNumber('+12133734253'); const localPhone = parsePhoneNumber('021-3373-4253', { regionCode: 'CN' });地区与国家代码转换
getCountryCodeForRegionCode
根据地区代码获取对应的国家代码。
参数:regionCode(string) - 两位字母的地区代码(如"DE"代表德国)
返回值:number - 对应的国家代码
getRegionCodeForCountryCode
根据国家代码获取对应的地区代码。
参数:countryCode(number) - 国家代码(如86代表中国)
返回值:string - 对应的地区代码
号码格式化
PhoneNumber对象提供多种格式化方法:
international:国际格式(如+1 213-373-4253)national:国内格式(如(213) 373-4253)e164:E.164格式(如+12133734253)rfc3966:RFC 3966格式(如tel:+1-213-373-4253)significant:仅包含有效数字(如2133734253)
号码类型判断
通过PhoneNumber对象的type属性可以获取号码类型,主要类型包括:
- fixed-line:固定电话
- mobile:移动电话
- toll-free:免费电话
- premium-rate: premium-rate号码
- voip:VoIP号码
其他实用方法
findNumbers
从文本中提取所有电话号码。
参数:
text(string):待提取的文本options(object):可选配置,包含地区代码等
getSupportedRegionCodes
获取所有支持的地区代码列表。
getAsYouType
创建实时输入解析器,支持边输入边格式化号码。
使用示例:
const asYouType = getAsYouType('US'); asYouType.input('213'); // 返回 "(213" asYouType.input('373'); // 返回 "(213) 373" asYouType.input('4253'); // 返回 "(213) 373-4253"实战应用示例
完整验证流程
// 解析号码 const phone = parsePhoneNumber('+8613800138000'); // 验证结果 if (phone.isValid()) { console.log('号码有效'); console.log('国际格式:', phone.international); console.log('号码类型:', phone.type); console.log('地区代码:', phone.regionCode); } else { console.log('号码无效'); }批量处理号码
const numbers = [ '+12133734253', '021-3373-4253', 'invalid-number' ]; numbers.forEach(number => { try { const phone = parsePhoneNumber(number, { regionCode: 'CN' }); console.log(`${number} -> ${phone.e164} (${phone.type})`); } catch (e) { console.log(`${number} -> 无效号码`); } });常见问题解决
地区代码自动检测
当解析不带国际前缀的号码时,务必提供正确的regionCode参数,否则可能导致解析错误。
处理特殊号码格式
对于包含分机号或其他特殊格式的号码,可以使用getNumberFrom方法提取主号码:
const mainNumber = getNumberFrom('+12133734253;ext=1234');浏览器与Node.js兼容性
awesome-phonenumber同时支持浏览器和Node.js环境,在浏览器中可直接通过src/index.js引入,Node.js环境则可通过标准require方式使用。
总结
awesome-phonenumber通过简洁的API为开发者提供了强大的电话号码处理能力,无论是简单的格式转换还是复杂的号码验证,都能轻松应对。掌握这些核心方法和参数,将帮助你在项目中高效处理全球各地的电话号码,提升用户体验和数据质量。
通过合理利用lib/index.js中提供的功能,结合本文介绍的使用技巧,你可以快速实现专业级的电话号码处理功能,为你的应用增添一份可靠保障。
【免费下载链接】awesome-phonenumberGoogle's libphonenumber pre-compiled with the closure compiler项目地址: https://gitcode.com/gh_mirrors/aw/awesome-phonenumber
创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考