JAVASCRIPT
Formatting US/Canadian Phone Numbers
Standardize phone number inputs into a consistent `(XXX) XXX-XXXX` format using JavaScript regex, enhancing user experience and data consistency.
function formatPhoneNumber(phoneNumberString) {
const cleaned = ('' + phoneNumberString).replace(/\D/g, ''); // Remove all non-digits
const match = cleaned.match(/^(\d{3})(\d{3})(\d{4})$/);
if (match) {
return '(' + match[1] + ') ' + match[2] + '-' + match[3];
}
return null; // Or return the original string if no match
}
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")); // null
How it works: This JavaScript function first cleans the input string by removing all non-digit characters using `/\D/g`. It then attempts to match the cleaned 10-digit string against the pattern `^(\d{3})(\d{3})(\d{4})$`. If a match is found, it uses the captured groups to construct the formatted `(XXX) XXX-XXXX` string; otherwise, it returns `null` or the original string if no complete 10-digit sequence is found.