2022-07-13 09:40:02 -07:00
|
|
|
/** List of supported E164 country codes. */
|
|
|
|
const COUNTRY_CODES = [
|
|
|
|
1,
|
|
|
|
44,
|
|
|
|
] as const;
|
|
|
|
|
|
|
|
/** Supported E164 country code. */
|
|
|
|
type CountryCode = typeof COUNTRY_CODES[number];
|
|
|
|
|
|
|
|
/** Check whether a given value is a country code. */
|
|
|
|
const isCountryCode = (value: any): value is CountryCode => COUNTRY_CODES.includes(value);
|
2022-03-21 11:09:01 -07:00
|
|
|
|
|
|
|
function removeFormattingFromNumber(number = '') {
|
|
|
|
if (number) {
|
|
|
|
return number.toString().replace(/\D/g, '');
|
|
|
|
}
|
|
|
|
|
|
|
|
return number;
|
|
|
|
}
|
|
|
|
|
2022-07-13 09:40:02 -07:00
|
|
|
function formatPhoneNumber(countryCode: CountryCode, phoneNumber = '') {
|
2022-03-21 11:09:01 -07:00
|
|
|
let formattedPhoneNumber = '';
|
2022-07-13 09:40:02 -07:00
|
|
|
const strippedPhone = removeFormattingFromNumber(phoneNumber);
|
2022-03-21 11:09:01 -07:00
|
|
|
|
|
|
|
for (let i = 0; i < strippedPhone.length && i < 10; i++) {
|
|
|
|
const character = strippedPhone.charAt(i);
|
|
|
|
if (i === 0) {
|
2022-07-13 09:40:02 -07:00
|
|
|
const prefix = `+${countryCode} (`;
|
2022-03-21 11:09:01 -07:00
|
|
|
formattedPhoneNumber += prefix + character;
|
|
|
|
} else if (i === 3) {
|
|
|
|
formattedPhoneNumber += `) ${character}`;
|
|
|
|
} else if (i === 6) {
|
|
|
|
formattedPhoneNumber += `-${character}`;
|
|
|
|
} else {
|
|
|
|
formattedPhoneNumber += character;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
return formattedPhoneNumber;
|
|
|
|
}
|
|
|
|
|
2022-07-13 09:40:02 -07:00
|
|
|
export {
|
|
|
|
COUNTRY_CODES,
|
|
|
|
CountryCode,
|
|
|
|
isCountryCode,
|
|
|
|
formatPhoneNumber,
|
|
|
|
};
|