format int to phone number

北战南征 提交于 2019-11-30 22:50:20

If you're saying that you want to do it on the client side, then given the phone number in a variable, you could do this:

http://jsfiddle.net/HZbXv/

var str = "0000000000";

var res = '(' + str.substr(0,3) + ')' + str.substr(3,3) + '-' + str.substr(6);

alert(res);

or this:

http://jsfiddle.net/HZbXv/1/

var str = "0000000000";

var res = str.replace(/(\d\d\d)(\d\d\d)(\d\d\d\d)/, '($1)$2-$3');

alert(res);

EDIT:

As noted by @Nick Craver The second version can be shortened up with:

var res = str.replace(/(\d{3})(\d{3})(\d{4})/, '($1)$2-$3');

As simple as this. Can use a simple if statement if you are going to deal with multiple numbers.

    YourVariable = YourVariable.replace(/(\d{1})(\d{3})(\d{3})(\d{4})/, "+$1 ($2)-$3-$4"); 

Displays: +1 (800)-555-5555

    YourVariable = YourVariable.replace(/(\d{3})(\d{3})(\d{4})/, "($1)-$2-$3"); 

Displays (555)-555-5555

If statement (my own code):

if (form.FaxNumber.length = 11){
    form.FaxNumber.value = form.FaxNumber.value.replace(/(\d{1})(\d{3})(\d{3})(\d{4})/, "+$1 ($2)-$3-$4");
}
if (form.FaxNumber.length = 10){
    form.FaxNumber.value = form.FaxNumber.value.replace(/(\d{3})(\d{3})(\d{4})/, "($1)-$2-$3");
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!