Skip to content

Instantly share code, notes, and snippets.

@sidisinsane
Last active July 17, 2023 12:53
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sidisinsane/9eaf44c777a1e00164a3f67ccf14a2ec to your computer and use it in GitHub Desktop.
Save sidisinsane/9eaf44c777a1e00164a3f67ccf14a2ec to your computer and use it in GitHub Desktop.
Formats a phone number using the libphonenumber-js library.
import parsePhoneNumber from "libphonenumber-js";
/**
* @typedef {Object} FormatPhoneNumberType - creates a new type named "FormatPhoneNumberType"
* @property {string} number - The phone number to format.
* @property {"NATIONAL" | "INTERNATIONAL" | "RFC3966"} [property="INTERNATIONAL"] - The desired formatting property.
*/
/**
* Formats a phone number using the libphonenumber-js library.
*
* @param {FormatPhoneNumberType} options - The options for formatting the phone number.
* @returns {string} - The formatted phone number string.
*
* @example
*
* const formattedNumber = formatPhoneNumber({
* number: '+12133734253',
* property: 'NATIONAL'
* });
* console.log(formattedNumber); // Output: "(213) 373-4253"
*/
export function formatPhoneNumber(options) {
const { number, property = "INTERNATIONAL" } = options;
const phoneNumber = parsePhoneNumber(number);
if (!phoneNumber || !phoneNumber.isValid()) {
return number;
}
return phoneNumber.format(property);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment