• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1# 电话号码格式化
2
3## 使用场景
4
5不同国家和地区的电话号码在号码位数、组合方式、呈现方式等都存在差异。同时,在不同环境和条件下,电话号码可能存在不同的拨打方式和号码格式。例如,在中国境内跨地区打电话,通常需要先输入“0”,再拨打区号和八位电话号码,而在香港或澳门拨打电话时,需要不同的拨号方式。
6
7通过号码格式化,可以根据需要给用户展示特定格式的电话号码。
8
9## 开发步骤
10
11电话号码格式化通过[PhoneNumberFormat](../reference/apis/js-apis-i18n.md#phonenumberformat8)的[format](../reference/apis/js-apis-i18n.md#format8)接口实现,具体开发步骤如下。
12
131. 导入模块。
14   ```ts
15   import I18n from '@ohos.i18n';
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
50
51**开发实例**
52
53```ts
54// 导入模块
55import I18n from '@ohos.i18n'
56
57// 格式化电话号码
58let phoneNumberFormat1 = new I18n.PhoneNumberFormat('CN');
59let formattedPhoneNumber1 = phoneNumberFormat1.format('158****2312'); // formattedPhoneNumber1: 158 **** 2312
60
61// RFC3966类型的电话号码
62let phoneNumberFormat2 = new I18n.PhoneNumberFormat('CN', {type: 'RFC3966'});
63let formattedPhoneNumber2 = phoneNumberFormat2.format('158****2312'); // formattedPhoneNumber2: tel:+86-158-****-2312
64
65// 判断电话号码是否有效
66let phoneNumberFormat3 = new I18n.PhoneNumberFormat('CN');
67let isValid = phoneNumberFormat3.isValidNumber('158****2312'); // isValid: true
68
69// 以某种语言显示号码归属地
70let phoneNumberFormat4 = new I18n.PhoneNumberFormat("CN");
71let locationName4 = phoneNumberFormat4.getLocationName('158****2312', 'en-GB') // locationName4: XiAn, Shanxi
72```
73