正则表达式在Javascript中重新格式化美国电话号码

Mat*_*t K 70 javascript regex

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

  • 123 4567890
  • (123)456-7890
  • (123)456-7890
  • 123 456 7890
  • 123.456.7890
  • (空白/空)
  • 1234567890

有一种简单的方法可以使用正则表达式来执行此操作吗?我正在寻找最好的方法来做到这一点.有没有更好的办法?

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

mae*_*ics 174

假设你想要格式" (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
}
Run Code Online (Sandbox Code Playgroud)

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

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"
Run Code Online (Sandbox Code Playgroud)

  • 除了“+1”之外,还有[国家/地区呼叫代码](https://en.wikipedia.org/wiki/List_of_country_calling_codes)。为了说明这一点,请将正则表达式中的“^(1|)”替换为“^(\d|)”,将“var intlCode”上的“+1”替换为“+${match[1]}”线。 (4认同)
  • 完善; 谢谢!但是,我改变了`return(!m)?null`到`return(!m)?""添加此功能后. (2认同)
  • 如何处理问题的一个很好的教训.我试图思考如何匹配所有可能的情况 - 你消除不相关的,看看是否有匹配.非常好. (2认同)
  • 仅供参考,这不适用于+ 1555-555-5555等数字 (2认同)

ios*_*seb 29

可能的方法:

function normalize(phone) {
    //normalize string and remove all unnecessary characters
    phone = phone.replace(/[^\d]/g, "");

    //check if number length equals to 10
    if (phone.length == 10) {
        //reformat and return phone number
        return phone.replace(/(\d{3})(\d{3})(\d{4})/, "($1) $2-$3");
    }

    return null;
}

var phone = '(123)4567890';
phone = normalize(phone); //(123) 456-7890
Run Code Online (Sandbox Code Playgroud)


Sea*_*ght 19

var x = '301.474.4062';

x = x.replace(/\D+/g, '')
     .replace(/(\d{3})(\d{3})(\d{4})/, '($1) $2-$3');
Run Code Online (Sandbox Code Playgroud)

这里的工作示例.


Dav*_*cum 8

这个答案借用了 maerics 的答案。它的主要区别在于它接受部分输入的电话号码并格式化已输入的部分。

phone = value.replace(/\D/g, '');
const match = phone.match(/^(\d{1,3})(\d{0,3})(\d{0,4})$/);
if (match) {
  phone = `${match[1]}${match[2] ? ' ' : ''}${match[2]}${match[3] ? '-' : ''}${match[3]}`;
}
return phone
Run Code Online (Sandbox Code Playgroud)


Jas*_*ing 7

向后思考

仅取最后一位数字(最多 10 位),忽略第一个“1”。

function formatUSNumber(entry = '') {
  const match = entry
    .replace(/\D+/g, '').replace(/^1/, '')
    .match(/([^\d]*\d[^\d]*){1,10}$/)[0]
  const part1 = match.length > 2 ? `(${match.substring(0,3)})` : match
  const part2 = match.length > 3 ? ` ${match.substring(3, 6)}` : ''
  const part3 = match.length > 6 ? `-${match.substring(6, 10)}` : ''    
  return `${part1}${part2}${part3}`
}
Run Code Online (Sandbox Code Playgroud)

输入/输出示例

formatUSNumber('+1333')
// (333)

formatUSNumber('333')
// (333)

formatUSNumber('333444')
// (333) 444

formatUSNumber('3334445555')
// (333) 444-5555
Run Code Online (Sandbox Code Playgroud)


mik*_*ryz 5

我正在使用此功能来格式化美国数字。

function formatUsPhone(phone) {

    var phoneTest = new RegExp(/^((\+1)|1)? ?\(?(\d{3})\)?[ .-]?(\d{3})[ .-]?(\d{4})( ?(ext\.? ?|x)(\d*))?$/);

    phone = phone.trim();
    var results = phoneTest.exec(phone);
    if (results !== null && results.length > 8) {

        return "(" + results[3] + ") " + results[4] + "-" + results[5] + (typeof results[8] !== "undefined" ? " x" + results[8] : "");

    }
    else {
         return phone;
    }
}
Run Code Online (Sandbox Code Playgroud)

它接受几乎所有可以想象的写美国电话号码的方式。结果被格式化为(987)654-3210 x123的标准格式