1# 电话号码格式化 2 3## 使用场景 4 5不同国家和地区的电话号码在号码位数、组合方式、呈现方式等都存在差异。同时,在不同环境和条件下,电话号码可能存在不同的拨打方式和号码格式。例如,在中国境内跨地区打电话,通常需要先输入“0”,再拨打区号和八位电话号码,而在香港或澳门拨打电话时,需要不同的拨号方式。 6 7通过号码格式化,可以根据需要给用户展示特定格式的电话号码。 8 9## 开发步骤 10 11电话号码格式化通过[PhoneNumberFormat](../reference/apis-localization-kit/js-apis-i18n.md#phonenumberformat8)的[format](../reference/apis-localization-kit/js-apis-i18n.md#format8)接口实现,具体开发步骤如下: 12 131. 导入模块。 14 ```ts 15 import { i18n } from '@kit.LocalizationKit'; 16 ``` 17 182. 创建PhoneNumberFormat对象。 19 20 构造函数支持通过PhoneNumberFormatOptions设置不同的电话号码格式,具体请参考表1。 21 22 ```ts 23 let phoneNumberFormat: i18n.PhoneNumberFormat = new i18n.PhoneNumberFormat(country: string, options?: PhoneNumberFormatOptions); 24 ``` 25 263. 电话号码格式化。 27 ```ts 28 let formattedPhoneNumber: string = phoneNumberFormat.format(phoneNumber: string); 29 ``` 30 314. 判断电话号码正确性和号码归属地。 32 ```ts 33 let isValidNumber: boolean = phoneNumberFormat.isValidNumber(phoneNumber: string); // 判断电话号码正确性 34 let locationName: string = phoneNumberFormat.getLocationName(number: string, locale: string); // 获取号码归属地 35 ``` 36 37**电话号码格式化选项** 38 39以电话号码158\*\*\*\*2312,所属国家代码CN为例,说明PhoneNumberFormatOptions不同取值和显示效果。 40 41**表1** 电话号码格式化的类型(type) 42 43| 取值 | 显示效果 | 44| -------- | -------- | 45| E164 | +86 158\*\*\*\*2312 | 46| INTERNATIONAL | +86 158 \*\*\*\* 2312 | 47| NATIONAL | 158 \*\*\*\* 2312 | 48| RFC3966 | tel:+86-158-\*\*\*\*-2312 | 49| TYPING | 158 \*\*\* | 50 51 52**开发实例** 53 54```ts 55// 导入模块 56import { i18n } from '@kit.LocalizationKit'; 57 58// 格式化电话号码 59let phoneNumberFormat: i18n.PhoneNumberFormat = new i18n.PhoneNumberFormat('CN'); 60let formattedPhoneNumber: string = phoneNumberFormat.format('158****2312'); // formattedPhoneNumber = '158 **** 2312' 61 62// RFC3966类型的电话号码 63let RFC3966Format: i18n.PhoneNumberFormat = new i18n.PhoneNumberFormat('CN', { type: 'RFC3966' }); 64formattedPhoneNumber = RFC3966Format.format('158****2312'); // formattedPhoneNumber = 'tel:+86-158-****-2312' 65 66// 判断电话号码是否有效 67let isValid: boolean = phoneNumberFormat.isValidNumber('158****2312'); // isValid = true 68 69// 以某种语言显示号码归属地 70let locationName: string = phoneNumberFormat.getLocationName('158****2312', 'en-GB'); // locationName = 'XiAn, Shanxi' 71 72// 拨号中的电话号码格式化 73let typingFormat: i18n.PhoneNumberFormat = new i18n.PhoneNumberFormat('CN', { type: 'TYPING' }); 74let phoneNumber: string = '0755453'; 75let formatResult: string = ''; // 通过如下方式对拨号中的号码格式化后,formatResult = '0755 453' 76for (let i = 0; i < phoneNumber.length; i++) { 77 formatResult += phoneNumber.charAt(i); 78 formatResult = typingFormat.format(formatResult); 79} 80``` 81