JAVASCRIPT
Validating and Formatting US Phone Numbers
Validate and optionally format US phone numbers (10 digits) using a flexible regular expression, accommodating various input styles for forms and data processing.
const formatUsPhoneNumber = (phoneNumber) => {
const cleaned = ('' + phoneNumber).replace(/\D/g, '');
const match = cleaned.match(/^(\d{3})(\d{3})(\d{4})$/);
if (match) {
return '(' + match[1] + ') ' + match[2] + '-' + match[3];
}
return null;
};
console.log(formatUsPhoneNumber('123-456-7890')); // (123) 456-7890
console.log(formatUsPhoneNumber('1234567890')); // (123) 456-7890
console.log(formatUsPhoneNumber(' (123) 456-7890 ')); // (123) 456-7890
console.log(formatUsPhoneNumber('123-45')); // null
How it works: The `formatUsPhoneNumber` function first cleans the input string by removing all non-digit characters. It then attempts to match the cleaned string against a regex that expects exactly 10 digits. If a match is found, it formats the number into '(XXX) XXX-XXXX'; otherwise, it returns `null`, indicating an invalid format or length.