如何更改电话号码的格式?

时间:2016-01-07 14:43:22

标签: javascript jquery

目前,格式是下一部手机

123-123-1123

我想要下一个表格:

(123)456-7890

如何将格式更改为我想要的任何形状?

<input class="" type="text" name="primary_phone" id="primary_phone" maxlength="10" placeholder="1234567890">
$("#primary_phone").blur(function() {
    text = $(this).val().replace(/(\d{3})(\d{3})(\d{4})/, "$1-$2-$3");
    $(this).val(text);
});

http://jsfiddle.net/Xxk3F/2864/

3 个答案:

答案 0 :(得分:1)

&#13;
&#13;
    var phone = "123-123-1123";
    var newPhone = "(" + phone.replace("-", ")");
    alert(newPhone);
&#13;
&#13;
&#13;

答案 1 :(得分:1)

转换由正则表达式处理,正则表达式构成文本.replace()函数的第一个参数,输出是第二个参数。这里需要改变第二个参数的格式。

$("#primary_phone").blur(function() {
  text = $(this).val().replace(/(\d{3})(\d{3})(\d{4})/, "($1)$2-$3");
  $(this).val(text);
});
//=> (123)456-7890

希望有所帮助。 :)

答案 2 :(得分:0)

$( "#primary_phone" ).blur(function() {
            text = $(this).val().replace(/(\d\d\d)(\d\d\d)(\d\d\d\d)/, '($1)$2-$3');
        $(this).val(text);
});

http://jsfiddle.net/m8sv89tg/