Regular Expression to reformat a US phone number in Javascript

后端 未结 13 2271
眼角桃花
眼角桃花 2020-12-02 07:32

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:

13条回答
  •  心在旅途
    2020-12-02 08:25

    thinking backwards

    Take the last digits only (up to 10) ignoring first "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}`
    }
    

    example input / output as you type

    formatUSNumber('+1333')
    // (333)
    
    formatUSNumber('333')
    // (333)
    
    formatUSNumber('333444')
    // (333) 444
    
    formatUSNumber('3334445555')
    // (333) 444-5555
    

提交回复
热议问题