diff --git a/.changeset/slimy-donkeys-float.md b/.changeset/slimy-donkeys-float.md new file mode 100644 index 0000000..0d2864c --- /dev/null +++ b/.changeset/slimy-donkeys-float.md @@ -0,0 +1,5 @@ +--- +'@thefakeorg/utils': patch +--- + +Add toPhoneE164 and fromPhoneE164 utilities diff --git a/packages/utils/src/index.ts b/packages/utils/src/index.ts index d9aae00..5b69923 100644 --- a/packages/utils/src/index.ts +++ b/packages/utils/src/index.ts @@ -1,8 +1,7 @@ /** * Return a slugified copy of a string. * - * @param {string} str The string to be slugified - * @return {string} The slugified string. + * @param string - The string to be slugified */ export function toSlug(str: string): string { let s = str; @@ -17,3 +16,32 @@ export function toSlug(str: string): string { s = s.length > 32 ? s.substr(0, 32) : s; return s; } + +/** + * Convert a phone number from E.164 format into (212)-555-9656 format + * @param phone - An unformatted 12-digit phone number string + */ +export function fromPhoneE164(phone: string): string { + if (phone.length === 12) { + return ( + phone.substring(2, 5) + + '-' + + phone.substring(5, 8) + + '-' + + phone.substring(8, 12) + ); + } else { + return phone; + } +} + +/** + * Convert a phone number into E.164 format. + */ +export function toPhoneE164(phone: string): string { + phone = phone.replace(/[^0-9]/g, ''); + if (phone.length === 10) { + phone = '1' + phone; + } + return '+' + phone; +}