正则表达式在Javascript中重新格式化美国电话号码 [英] Regular Expression to reformat a US phone number in Javascript

查看:115
本文介绍了正则表达式在Javascript中重新格式化美国电话号码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻找重新格式化(替换,而不是验证 - 有许多用于验证的参考)电话号码以便在Javascript中显示。以下是部分数据的示例:

I'm looking to reformat (replace, not validate - there are many references for validating) a phone number for display in Javascript. Here's an example of some of the data:


  • 123 4567890

  • (123)456-7890

  • (123)456-7890

  • 123 456 7890

  • 123.456.7890

  • (空白/ null)

  • 1234567890

  • 123 4567890
  • (123) 456-7890
  • (123)456-7890
  • 123 456 7890
  • 123.456.7890
  • (blank/null)
  • 1234567890

是否容易使用正则表达式来做这个的方法?我正在寻找最好的方法来做到这一点。有更好的方法吗?

Is there an easy way to use a regular expression to do this? I'm looking for the best way to do this. Is there a better way?

我想将数字重新格式化为以下内容:(123)456-7890

I want to reformat the number to the following: (123) 456-7890

推荐答案

假设您想要格式(123)456-7890

function formatPhoneNumber(phoneNumberString) {
  var cleaned = ('' + phoneNumberString).replace(/\D/g, '')
  var match = cleaned.match(/^(\d{3})(\d{3})(\d{4})$/)
  if (match) {
    return '(' + match[1] + ') ' + match[2] + '-' + match[3]
  }
  return null
}

这是一个允许可选<$ c的版本$ c> +1 国际代码:

Here's a version that allows the optional +1 international code:

function formatPhoneNumber(phoneNumberString) {
  var cleaned = ('' + phoneNumberString).replace(/\D/g, '')
  var match = cleaned.match(/^(1|)?(\d{3})(\d{3})(\d{4})$/)
  if (match) {
    var intlCode = (match[1] ? '+1 ' : '')
    return [intlCode, '(', match[2], ') ', match[3], '-', match[4]].join('')
  }
  return null
}
formatPhoneNumber('+12345678900') // => "+1 (234) 567-8900"
formatPhoneNumber('2345678900')   // => "(234) 567-8900"

这篇关于正则表达式在Javascript中重新格式化美国电话号码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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