Rendering formatted phone number with regex

I am writing a pipe in Angular that renders the appropriate formatted phone number depending on what is contained in the string.

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)

My current 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) => item != undefined);
arrOfDigits = arrOfDigits.filter((item, index) => 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 <= 2) { console.log(`${arrOfDigits[1]} (${arrOfDigits[2]}) ${arrOfDigits[3]}-${arrOfDigits[4]}`) } else { console.log(`(${arrOfDigits[1]}) ${arrOfDigits[2]}-${arrOfDigits[3]} ${arrOfDigits[4]}`) }
}

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.

Thank you.

1

1 Answer

I've created a directive for this purpose.

GitHub Gist

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

You Might Also Like