Rendering formatted phone number with regex
Matthew Barrera
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.
11 Answer
I've created a directive for this purpose.