电话号码格式javascript [英] Phone number format javascript

查看:91
本文介绍了电话号码格式javascript的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用正则表达式格式化一些电话号码.我存储的电话号码长度不同,所有电话号码都有其国家代码.可以说一个数字如下:00460708186681.我希望将其格式设置为:+46(0)708-18 6681.前三组很简单:

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})

现在为可能的每一对添加另一对(\d{2})?(注意?").因此,如果最大对数为3,则请执行以下操作:

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.

这篇关于电话号码格式javascript的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆