-
Notifications
You must be signed in to change notification settings - Fork 0
/
phoneNumberUtil.ts
60 lines (47 loc) · 1.76 KB
/
phoneNumberUtil.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
import { templateFormatter } from 'input-format'
/**
* This code should handle a variety of US phone number formats:
* - with or without country code 1
* - with or without leading +
* - less than the required number of digits
* - with or without punctuation
*
* This code is used by [[`PhoneInput`]].
*/
/** The number of phone number digits that are displayed. */
const visibleLen = 10
/** The number of phone number digits including the US/Canada country code. */
const lenWithCountryCode = visibleLen + 1
/** The template used for formatting phone numbers. */
const template = '(xxx) xxx-xxxx'
/** @internal */
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment, @typescript-eslint/no-unsafe-call
const formatter: (s: string) => { text: string } = templateFormatter(template)
export const AdvancedPhoneNumberUtil = {
visibleLen,
lenWithCountryCode,
template,
formatter,
}
/**
* Takes in a phone number in any format and converts it to an 11-digit string that
* starts with the US/Canada country code of 1.
*/
export function normalizePhoneNumber(phoneNumber: string): string {
let num = phoneNumber.replace(/[^0-9]/g, '')
if (num.length > 0 && !num.startsWith('1')) num = `1${num}`
if (num.length > lenWithCountryCode) {
num = num.substring(0, lenWithCountryCode)
}
return num
}
/** Format a phone number for display. Uses [[`normalizePhoneNumber`]]. */
export function formatPhoneNumber(phoneNumber: string | undefined | null): string {
if (!phoneNumber) return ''
const normalized = normalizePhoneNumber(phoneNumber)
let noCountry = normalized
if (noCountry.length > 0 && noCountry.startsWith('1')) {
noCountry = noCountry.substring(1)
}
return formatter(noCountry).text
}