我正在寻找一种重新格式化电话号码以在 Javascript 中显示的方法。以下是一些数据的示例:
00-22 345 991
555922134
12450-123948
我想将数字重新格式化为以下 3 种长度格式,例如:555-922-134
假设可以忽略破折号和空格,最后两个 block 的长度可以是 2,例如:002-234-59-91
或 124-501-349-48
最佳答案
您可以使用带前瞻性的正则表达式。
Positive Lookahead 查找等号后的模式,但不将其包含在匹配中。
x(?=y)
Matches 'x' only if 'x' is followed by 'y'. This is called a lookahead.
For example,
/Jack(?=Sprat)/
matches 'Jack' only if it is followed by 'Sprat'./Jack(?=Sprat|Frost)/
matches 'Jack' only if it is followed by 'Sprat' or 'Frost'. However, neither 'Sprat' nor 'Frost' is part of the match results.
function format(s) {
return s.toString().replace(/\D/g, '').replace(/\d{2,3}(?=..)/g, '$&-');
}
console.log(format('00-22 345 991'));
console.log(format('555922134'));
console.log(format('12450-123948'));
console.log(format(123456789));
console.log(format(12345678901));
console.log(format(1234567));
关于javascript - 将字符串格式化为特定格式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42330936/