JAVASCRIPT
Extracting and Normalizing Phone Numbers
Learn to extract and normalize various phone number formats into a consistent `(XXX) XXX-XXXX` pattern using JavaScript regular expressions.
function normalizePhoneNumber(input) {
const digits = input.replace(/\D/g, ''); // Remove all non-digits
const match = digits.match(/^(\d{3})(\d{3})(\d{4})$/);
if (match) {
return `(${match[1]}) ${match[2]}-${match[3]}`;
} else {
return null; // Or throw an error, or return original if not matching pattern
}
}
console.log(normalizePhoneNumber(" (123) 456-7890 ext. 123 ")); // Output: "(123) 456-7890"
console.log(normalizePhoneNumber("123.456.7890")); // Output: "(123) 456-7890"
console.log(normalizePhoneNumber("1234567890")); // Output: "(123) 456-7890"
console.log(normalizePhoneNumber("invalid phone")); // Output: null
How it works: This snippet first cleans the input by removing all non-digit characters using `replace(/\D/g, '')`. Then, it applies a regex `/^(\d{3})(\d{3})(\d{4})$/` to capture exactly 10 digits into three distinct groups (area code, prefix, and line number). If a match is found, it formats these captured groups into a standardized `(XXX) XXX-XXXX` string. This is useful for consistent display or storage of phone numbers.