I'm currently displaying phone numbers like 2124771000. However, I need the number to be formatted in a more human-readable form, for example: 212-477-1000. Here's my current HTML:

<p class="phone">2124771000</p>

推荐答案

Simple: http://jsfiddle.net/Xxk3F/3/

$('.phone').text(function(i, text) {
    return text.replace(/(\d{3})(\d{3})(\d{4})/, '$1-$2-$3');
});

Or: http://jsfiddle.net/Xxk3F/1/

$('.phone').text(function(i, text) {
    return text.replace(/(\d\d\d)(\d\d\d)(\d\d\d\d)/, '$1-$2-$3');
});

Note: The .text() method cannot be used on input elements. For input field text, use the .val() method.

Jquery相关问答推荐

在不同的行插入不同的值

我需要在上一个表格单元格中显示计算结果

Flask,如何为ajax调用返回成功状态码

document.querySelector 一个元素中的多个数据属性

如何使用 jQuery 获取所有 ID?

[本机代码]是什么意思?

将 HTML5 Canvas 转换为要上传的文件?

在 JavaScript 中解析 URL

如何使用 jQuery 将表格的一行滚动到视图 (element.scrollintoView) 中?

我们如何在不重新加载页面的情况下使用 javascript/jQuery 更新 URL 或查询字符串?

在网络浏览器中,onblur 和 onfocusout 有什么区别?

如何在 Jquery 中将 delay() 与 show() 和 hide() 一起使用

如何在 JQuery 中 Select 除单击元素之外的所有类?

如何使用 javascript 擦除所有内联样式并仅保留 css 样式表中指定的样式?

如何在 jQuery 中 Select this中的元素?

jQuery : eq() 与 get()

如何使锚链接不可点击或禁用?

jQuery DataTables:控制表格宽度

为什么要使用发布/订阅模式(在 JS/jQuery 中)?

如何使用新的 JSON 数据手动更新数据表