/ Published in: JavaScript
Formats a 10-digit phone number into a good format (123) 555-1234
Expand |
Embed | Plain Text
Copy this code and paste it in your HTML
/** * Format phone numbers */ function formatPhone(phonenum) { var regexObj = /^(?:\+?1[-. ]?)?(?:\(?([0-9]{3})\)?[-. ]?)?([0-9]{3})[-. ]?([0-9]{4})$/; if (regexObj.test(phonenum)) { var parts = phonenum.match(regexObj); var phone = ""; if (parts[1]) { phone += "+1 (" + parts[1] + ") "; } phone += parts[2] + "-" + parts[3]; return phone; } else { //invalid phone number return phonenum; } }
URL: http://grover.open2space.com/content/javascript-formatting-phone-numbers-and-postal-codes