FormatPhoneNumber [格式化电话号码]
# 介绍
给定 10 个数字,返回格式化为 (XXX) XXX-XXXX
的电话号码。
# 实现
# JavaScript
// function that takes 10 digits and returns a string of the formatted phone number
// e.g.: 1234567890 -> (123) 456-7890
const formatPhoneNumber = (numbers) => {
const numbersString = numbers.toString()
if ((numbersString.length !== 10) || isNaN(numbersString)) {
// return "Invalid phone number."
throw new TypeError('Invalid phone number.')
}
const arr = '(XXX) XXX-XXXX'.split('')
Array.from(numbersString).forEach(n => {
arr[arr.indexOf('X')] = n
})
return arr.join('')
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
2
3
4
5
6
7
8
9
10
11
12
13
14
15
编辑 (opens new window)
上次更新: 2022/10/20, 20:45:42