JAVASCRIPT
Validate and Format North American Phone Numbers
Validate common North American phone number formats and consistently reformat them using a flexible JavaScript regex with capture groups.
function formatPhoneNumber(phoneNumber) {
const phoneRegex = /^\(?([0-9]{3})\)?[-. ]?([0-9]{3})[-. ]?([0-9]{4})$/;
const match = phoneRegex.exec(phoneNumber);
if (match) {
// Reformat to (XXX) XXX-XXXX
return `(${match[1]}) ${match[2]}-${match[3]}`;
} else {
return null; // Invalid format
}
}
// Examples:
console.log(formatPhoneNumber("123-456-7890")); // "(123) 456-7890"
console.log(formatPhoneNumber("(123) 456-7890")); // "(123) 456-7890"
console.log(formatPhoneNumber("1234567890")); // "(123) 456-7890"
console.log(formatPhoneNumber("123.456.7890")); // "(123) 456-7890"
console.log(formatPhoneNumber("555-BAD-NUMBER")); // null
How it works: This JavaScript snippet validates and formats North American phone numbers. The regex `^\(?([0-9]{3})\)?[-. ]?([0-9]{3})[-. ]?([0-9]{4})$` captures the three main digit groups (area code, prefix, line number) while allowing optional parentheses, hyphens, dots, or spaces as separators. The `exec()` method captures these groups, allowing the function to reconstruct the phone number into a consistent `(XXX) XXX-XXXX` format if valid. If the number doesn't match the pattern, it returns `null`.