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).
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.
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.
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/