10 Digit String to Phone Format


/ Published in: JavaScript
Save to your folder(s)

Formats a 10-digit phone number into a good format (123) 555-1234


Copy this code and paste it in your HTML
  1. /**
  2.  * Format phone numbers
  3. */
  4. function formatPhone(phonenum) {
  5. var regexObj = /^(?:\+?1[-. ]?)?(?:\(?([0-9]{3})\)?[-. ]?)?([0-9]{3})[-. ]?([0-9]{4})$/;
  6. if (regexObj.test(phonenum)) {
  7. var parts = phonenum.match(regexObj);
  8. var phone = "";
  9. if (parts[1]) { phone += "+1 (" + parts[1] + ") "; }
  10. phone += parts[2] + "-" + parts[3];
  11. return phone;
  12. }
  13. else {
  14. //invalid phone number
  15. return phonenum;
  16. }
  17. }

URL: http://grover.open2space.com/content/javascript-formatting-phone-numbers-and-postal-codes

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.