title: Rendering formatted phone number with regex
body: <p>I am writing a pipe in Angular that renders the appropriate formatted phone number depending on what is contained in the string. </p>
  
  <p>Input: string
  possible cases that need to be rendered: 
  +1 (123) 456-7891 (country code + tendigit)
  (123) 456-7891 (ten digit)
  (123) 456-7891 ext1234 (tendigit with extension)
  + 1 (123) 456-7891 ext1234 (country code, tendigit, extension)</p>
  
  <p>My current code:</p>
  
  <pre><code>const rawPhoneNumber = '1(626) 423-3343 ex123'
  const pattern = /(\d{1})?([a-zA-Z\d]{3})([a-zA-Z\d]{3})([a-zA-Z\d]{4})(.*)/
  const matches = rawPhoneNumber.replace(/[\W_]*/g, '').match(pattern);
  let arrOfDigits = matches.filter((item, index) =&gt; item != undefined);
  arrOfDigits = arrOfDigits.filter((item, index) =&gt; item.length)
  
  // simple Phone
  if (arrOfDigits.length === 4) {
    console.log(`(${arrOfDigits[1]}) ${arrOfDigits[2]}-${arrOfDigits[3]}`)  
  }
  // prephonesuffix
  if (arrOfDigits.length === 6) {
    console.log(`+${arrOfDigits[1]} (${arrOfDigits[2]}) ${arrOfDigits[3]}-${arrOfDigits[4]} ${arrOfDigits[5]}`)
  }
  // pre or suff
  if (arrOfDigits.length === 5) { 
    if (arrOfDigits[1].length &lt;= 2) {
      console.log(`${arrOfDigits[1]} (${arrOfDigits[2]}) ${arrOfDigits[3]}-${arrOfDigits[4]}`)
    } else {
      console.log(`(${arrOfDigits[1]}) ${arrOfDigits[2]}-${arrOfDigits[3]} ${arrOfDigits[4]}`)
    }
  }
  </code></pre>
  
  <p>My issue is, this is very easy to break if the number is not perfect. I would like any suggestions as to how I could cover more cases. </p>
  
  <p>Thank you. </p>