Phone number format javascript

泄露秘密 提交于 2019-12-11 06:30:35

问题


I'm trying to format some phone numbers with regexp. The phone numbers i have stored are of diffrent length and all phone numbers have their country codes. Lets say a number looks like this: 00460708186681. I want that one to be formatted as: +46 (0)708-18 66 81. The first three groups are easy:

/00([\d]{2})([\d]{1})([\d]{3})/

Because the beginning of the number will always be the same. It's the last part where i dont know the length of the remaining chars (and i want them to be divided into groups of two).


回答1:


Start with the following regex as your base:

00(\d{2})(\d)(\d{3})(\d{2})

Now add another pair (\d{2})? (note the '?') for every pair it's possible to have. So if the maximum number of pairs is 3, you do the following:

00(\d{2})(\d)(\d{3})(\d{2})(\d{2})?(\d{2})?

It's not pretty, but you need to do it that way in order to get them grouped correctly. Or you could simply do:

00(\d{2})(\d)(\d{3})((?:\d{2}){2,4}) // In this case it's 2 to 4 pairs of digits on the end.

To match the string, then you can manually add spaces in the last group which will contain all the digits after your initial formatting.




回答2:


Regex is not the best solution here. Use this:

var num = new String("00460708186681"),
    i = 2,
    p,
    res = "+"+num.substr(i,2)+" ("+num.charAt(i+=2)+")"+num.substr(++i,3)+"-"+num.substr(i+=3,2);
while (p=num.substr(i+=2,2))
    res+= "\u00A0"+p;
return res;

Which will work for infinitely long numbers. A regex can't do that.




回答3:


Here is solution :

Javascript:

var num="00460708186681";
var res=num.replace(/([0+]{2})([1-9]{2})([\d]{1})([\d]{3})([\d]{2})([\d]{2})([\d]{2})/g,'+$2($3)-$4 $5 $6 $7');
alert(res);

Try above script on http://codebins.com/



来源:https://stackoverflow.com/questions/11519699/phone-number-format-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!