Posted By

cpres on 06/17/12


Tagged

regex phone convert


Versions (?)

10 Digit String to Phone Format


 / Published in: JavaScript
 

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

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

  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. }

Report this snippet  

You need to login to post a comment.