How to format phone numbers to the US format in TypeScript

1 Answer

0 votes
function formatUSPhoneNumbers(phonenumber: string): string {
    // Remove all non-digit chars
    const digits: string = phonenumber.replace(/\D/g, '');
   
    // Apply (XXX) XXX-XXXX format
   
    // match: the full matched string (e.g., "1234567890")
    // countrycode: match from the first optional group (1)?
    // x, y, z: matches from the next three-digit groups of 3, 3, and 4 digits respectively
 
    return digits.replace(/^(1)?(\d{3})(\d{3})(\d{4})$/, (match, countrycode, x, y, z) => {
        const prefix = countrycode ? '+1 ' : '';
        return `${prefix}(${x}) ${y}-${z}`;
    });
}
 
console.log(formatUSPhoneNumbers('AZ123-456-7890Y'));
console.log(formatUSPhoneNumbers('123.456.7890'));
console.log(formatUSPhoneNumbers('+1 123 456 7890'));

 
 
/*
run:
 
"(123) 456-7890" 
"(123) 456-7890" 
"+1 (123) 456-7890" 
 
*/

 



answered Jul 1, 2025 by avibootz
...