javascript - 将字符串格式化为特定格式

标签 javascript

我正在寻找一种重新格式化电话号码以在 Javascript 中显示的方法。以下是一些数据的示例:

00-22 345 991

555922134

12450-123948

我想将数字重新格式化为以下 3 种长度格式,例如:555-922-134

假设可以忽略破折号和空格,最后两个 block 的长度可以是 2,例如:002-234-59-91124-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/

相关文章:

javascript - 动态地将 DIV 添加到模式中

javascript - jQuery Colorbox 的问题

javascript - xhr 在 onreadystatechange 中是否始终可以作为参数的属性使用?使用哪一个?

javascript - 完整的 Javascript Ajax php 混淆

javascript - JQuery:在元素的 HTML 之前附加项目

javascript - 如何使用nodejs获取json值

javascript - 如何为我的 php Web 应用程序提供桌面通知?

javascript - 无法访问在 Javascript 脚本标记内的 EJS 中声明的 json 数组的项目

javascript - "HTML tidy"有 JavaScript 或 Ruby 版本吗?

javascript - 如何检查字符串 "should not contain leading, trailing, and mutliple commas in middle"