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