Formatting phone numbers in JavaScript is essential for creating clean, user-friendly inputs and displaying consistent contact information across your application. A typical approach involves stripping out non-numeric characters and then reformatting the digits to match a desired pattern, such as the standard U.S. format. Here's a simple example:
function formatPhoneNumber(number) {
const cleaned = ('' + number).replace(/\D/g, '');
const match = cleaned.match(/^(\d{3})(\d{3})(\d{4})$/);
if (match) {
return `(${match[1]}) ${match[2]}-${match[3]}`;
}
return number;
}
console.log(formatPhoneNumber("123-456-7890")); // (123) 456-7890
This function removes all non-digit characters and formats the number as (123) 456-7890 if it contains exactly 10 digits. For more advanced formatting, including handling international numbers and edge cases, refer to this comprehensive guide on JavaScript phone number formatting at MildDev—it covers everything from basic patterns to using libraries like libphonenumber-js for robust validation and formatting.