Skip to content

Instantly share code, notes, and snippets.

@lenivene
Last active August 20, 2023 16:14
Show Gist options
  • Save lenivene/a481bb414a7db97b539f288d6375fc29 to your computer and use it in GitHub Desktop.
Save lenivene/a481bb414a7db97b539f288d6375fc29 to your computer and use it in GitHub Desktop.
The provided function `formatPhoneNumber` takes a phone number as input and returns a formatted version of that phone number.
export const formatPhoneNumberHelper = (number: string): string => {
const cleanedNumber: string = String(number).replace(/\D/g, "");
// Check if the number has at least 10 digits
if (cleanedNumber.length < 10) {
return number;
}
// Extract the DDI (the first digits, can be 2 or 3)
const DDI: string = cleanedNumber.slice(
0,
2 + (cleanedNumber.length > 13 ? 1 : 0)
);
// Extract the DDD (the next digits)
const DDD: string = cleanedNumber.slice(DDI.length, DDI.length + 2);
// Extract the remaining phone number
const phoneNumber: string = cleanedNumber.slice(DDI.length + DDD.length);
let phoneNumberFormatted = phoneNumber;
// Format phone number to return "9 9999-9999"
if (phoneNumber.length === 9) {
// Split the number into parts
const part1 = phoneNumber.slice(0, 1);
const firstPartPhoneNumber = phoneNumber.slice(1, 5);
const secondPartPhoneNumber = phoneNumber.slice(5);
// Concatenate the formatted parts
phoneNumberFormatted = `${part1} ${firstPartPhoneNumber}-${secondPartPhoneNumber}`;
}
// Format the number as desired
const formattedNumber: string = `+${DDI} (${DDD}) ${phoneNumberFormatted}`;
return formattedNumber;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment