Last active
July 17, 2023 12:53
-
-
Save sidisinsane/9eaf44c777a1e00164a3f67ccf14a2ec to your computer and use it in GitHub Desktop.
Formats a phone number using the libphonenumber-js library.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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