JAVASCRIPT
Standardize Phone Number Formatting
Use JavaScript and Regex to automatically format a raw 10-digit phone number into a standardized, readable pattern like (XXX) XXX-XXXX for better user experience.
function formatPhoneNumber(phoneNumber) {
// Remove all non-digit characters
const cleanNumber = phoneNumber.replace(/\D/g, '');
// Match 10 digits and reformat
const regex = /^(\d{3})(\d{3})(\d{4})$/;
const match = cleanNumber.match(regex);
if (match) {
return `(${match[1]}) ${match[2]}-${match[3]}`;
}
// Return original if not a 10-digit number or not matching pattern
return phoneNumber;
}
console.log(formatPhoneNumber("123-456-7890")); // Expected Output: (123) 456-7890
console.log(formatPhoneNumber("+1 (987) 654-3210")); // Expected Output: (987) 654-3210
console.log(formatPhoneNumber("5551234")); // Expected Output: 5551234 (original returned)
How it works: This JavaScript function formats phone numbers. It first cleans the input by removing all non-digit characters using `/\D/g`. Then, it applies a regex `^(\d{3})(\d{3})(\d{4})$` to capture three groups of digits (3, 3, and 4 digits respectively) if the number is exactly 10 digits long. If a match is found, it constructs the standardized string `(XXX) XXX-XXXX` using the captured groups.