您可以随时使用它来直接拉出号码。
咖啡脚本:
console.log number.match ///
# Match the start of the string.
^
# Get the first 3 digits.
\(?(?=\d{3})(\d{3})[).\-\s]*
# Get the next 3 digits.
(\d{3})[.\-\s]*
# Get the last 4 digits
(\d{4})
# End of the number
$
///
Javascript(或节点):
console.log(number.match(/^\(?(?=\d{3})(\d{3})[).\-\s]*(\d{3})[.\-\s]*(\d{4})$/));
以下是我在 CoffeeScript 中运行的测试用例,以确保它有效:
exports '1234567890'
exports '123 456 7890'
exports '123.456.7890'
exports '123 456.7890'
exports '123.456 7890'
exports '123456.7890'
exports '123.4567890'
exports '123456. 7890'
exports '123-456-7890'
exports '123 456-7890'
exports '123-456 7890'
exports '123456-7890'
exports '123-4567890'
exports '(123)456-7890'
exports '(123)4567890'
exports '(123) 4567890'
exports '(123)456 7890'
exports '(123) 456 7890'
exports '(123) 4567890'
他们的输出:
1234567890
[ '1234567890',
'123',
'456',
'7890',
index: 0,
input: '1234567890' ]
123 456 7890
[ '123 456 7890',
'123',
'456',
'7890',
index: 0,
input: '123 456 7890' ]
123.456.7890
[ '123.456.7890',
'123',
'456',
'7890',
index: 0,
input: '123.456.7890' ]
123 456.7890
[ '123 456.7890',
'123',
'456',
'7890',
index: 0,
input: '123 456.7890' ]
123.456 7890
[ '123.456 7890',
'123',
'456',
'7890',
index: 0,
input: '123.456 7890' ]
123456.7890
[ '123456.7890',
'123',
'456',
'7890',
index: 0,
input: '123456.7890' ]
123.4567890
[ '123.4567890',
'123',
'456',
'7890',
index: 0,
input: '123.4567890' ]
123456. 7890
[ '123456. 7890',
'123',
'456',
'7890',
index: 0,
input: '123456. 7890' ]
123-456-7890
[ '123-456-7890',
'123',
'456',
'7890',
index: 0,
input: '123-456-7890' ]
123 456-7890
[ '123 456-7890',
'123',
'456',
'7890',
index: 0,
input: '123 456-7890' ]
123-456 7890
[ '123-456 7890',
'123',
'456',
'7890',
index: 0,
input: '123-456 7890' ]
123456-7890
[ '123456-7890',
'123',
'456',
'7890',
index: 0,
input: '123456-7890' ]
123-4567890
[ '123-4567890',
'123',
'456',
'7890',
index: 0,
input: '123-4567890' ]
(123)456-7890
[ '(123)456-7890',
'123',
'456',
'7890',
index: 0,
input: '(123)456-7890' ]
(123)4567890
[ '(123)4567890',
'123',
'456',
'7890',
index: 0,
input: '(123)4567890' ]
(123) 4567890
[ '(123) 4567890',
'123',
'456',
'7890',
index: 0,
input: '(123) 4567890' ]
(123)456 7890
[ '(123)456 7890',
'123',
'456',
'7890',
index: 0,
input: '(123)456 7890' ]
(123) 456 7890
[ '(123) 456 7890',
'123',
'456',
'7890',
index: 0,
input: '(123) 456 7890' ]
(123) 4567890
[ '(123) 4567890',
'123',
'456',
'7890',
index: 0,
input: '(123) 4567890' ]
如果number.match
返回null
该代码,则它不是有效数字。所以这是一种简单的检查方法,然后已经解析了数字。
如果您想允许a-z
,只需将所有\d
条目更改为[\d\w]
. (见此)