@synotech/utils
Version:
a collection of utilities for internal use
41 lines (36 loc) • 1.29 kB
text/typescript
import { CountryCode, parsePhoneNumber } from 'libphonenumber-js';
export interface PhoneNumberInterface {
phoneNumber: string;
countryCode: CountryCode;
}
/**
* Returns the international format of a phone number.
* @module phoneNumberGetInternationalString
* @param phoneNumberObject - An object containing the phone number and country code.
* @returns The international format of the phone number as a string.
*
* @example
* const phoneNumberObject = {
* phoneNumber: '+1234567890',
* countryCode: 'US',
* }
*
* const internationalPhoneNumber = phoneNumberGetInternationalString(phoneNumberObject);
* console.log(internationalPhoneNumber); // Output: { national: '1234567890', international: '+1 234-567-890' }
*/
export function phoneNumberGetInternationalString(
phoneNumberObject: PhoneNumberInterface
): { national: string | undefined, international: string | undefined } {
const { phoneNumber, countryCode } = phoneNumberObject
if (phoneNumber && countryCode) {
const formattedPhoneNumber = parsePhoneNumber(phoneNumber, countryCode);
return {
national: formattedPhoneNumber?.formatNational() ?? phoneNumber,
international: formattedPhoneNumber?.formatInternational(),
}
}
return {
national: phoneNumber,
international: undefined,
}
}