需要正则表达式帮助
我正在使用以下正则表达式将数字转换为电话格式。
telephoneNumber = '1234567890';
var number = telephoneNumber.replace(/\D/g,'');
newNumber = number.replace(/^(\d{3})(\d{3})(\d{4})$/, '($1)$2-$3'); // (123)456-7890
问题是如果telephoneNumber.length大于10那么它什么也不做。我想在电话号码末尾添加额外的数字。
例如:
change 1234567890 to (123)456-7890
change 1234567890111 to (123)456-7890111
我应该在上面的正则表达式中更改什么。
谢谢。
I am using following regex to convert digits into phone format.
telephoneNumber = '1234567890';
var number = telephoneNumber.replace(/\D/g,'');
newNumber = number.replace(/^(\d{3})(\d{3})(\d{4})$/, '($1)$2-$3'); // (123)456-7890
Problem is that if telephoneNumber.length is greater than 10 then it does nothing. I want to add extra digits in the end of the phone number.
For example:
change 1234567890 to (123)456-7890
change 1234567890111 to (123)456-7890111
What should I change in above regex.
Thanks.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
尝试将最后一行更改为:
newNumber = number.replace(/^(\d{3})(\d{3})(\d{4,})$/, '($1)$2-$3');
我只是在
\d{4
之后添加了一个逗号,这告诉它需要 4 位或更多数字。另外,我经常使用这个网站来测试我的正则表达式:http://gskinner.com/RegExr/非常方便。
Try changing the last line to this:
newNumber = number.replace(/^(\d{3})(\d{3})(\d{4,})$/, '($1)$2-$3');
I just added a comma after the
\d{4
this tells it to take 4 or more digits.Also, I often use this site to test out my regex's: http://gskinner.com/RegExr/ It's VERY handy.
我看到您想要使用正则表达式的唯一原因是为了验证,但是如果您只是尝试将字符串格式化为电话号码,为什么不只使用 Javascript 电话号码格式化程序
The only reason I can see you wanting to use a Regex is for validation, however if you're just trying to format the string to a phone number, why not just use a Javascript Phone Number Formatter