Phone formatting in JS


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

Shameless port of this PHP function: http://snipplr.com/view/3680/format-phone/


Copy this code and paste it in your HTML
  1. /**
  2. * Ported by Andres Galindo (http://andresgalindo.us)
  3. * Shameless port of http://www.danielkassner.com/2010/05/21/format-us-phone-number-using-php
  4. **/
  5. function format_phone (phone, convert, trim){
  6. if( typeof convert == 'undefined' ){
  7. convert = true;
  8. }
  9.  
  10. if( typeof trim == 'undefined' ){
  11. trim = true;
  12. }
  13.  
  14. // Strip out any extra characters that we do not need only keep letters and numbers
  15. phone = phone.replace(/[^0-9A-Za-z]/, "");
  16.  
  17. // Do we want to convert phone numbers with letters to their number equivalent?
  18. if ( convert == true && phone.match(/[a-zA-Z]/) ) {
  19. var replace = {
  20. '2': ['a','b','c'],
  21. '3': ['d','e','f'],
  22. '4': ['g','h','i'],
  23. '5': ['j','k','l'],
  24. '6': ['m','n','o'],
  25. '7': ['p','q','r','s'],
  26. '8': ['t','u','v'],
  27. '9': ['w','x','y','z']
  28. }
  29.  
  30. // Replace each letter with a number
  31. // Notice this is case insensitive with the str_ireplace instead of str_replace
  32. for( digit in replace ){
  33. var regex = new RegExp('[' + replace[digit].join('') + ']', 'ig');
  34. phone = phone.replace(regex, digit);
  35. }
  36. }
  37.  
  38. // If we have a number longer than 11 digits cut the string down to only 11
  39. // This is also only ran if we want to limit only to 11 characters
  40. if( trim == true && phone.length > 11 ) {
  41. phone = phone.substr(0, 11);
  42. }
  43.  
  44. // Perform phone number formatting here
  45. if( phone.length == 7 ) {
  46. return phone.replace(/([0-9a-zA-Z]{3})([0-9a-zA-Z]{4})/, "$1-$2");
  47. }else if( phone.length == 10 ) {
  48. return phone.replace(/([0-9a-zA-Z]{3})([0-9a-zA-Z]{3})([0-9a-zA-Z]{4})/, "($1) $2-$3");
  49. }else if( phone.length == 11 ) {
  50. return phone.replace(/([0-9a-zA-Z]{1})([0-9a-zA-Z]{3})([0-9a-zA-Z]{3})([0-9a-zA-Z]{4})/, "$1($2) $3-$4");
  51. }
  52.  
  53. // Return original phone if not 7, 10 or 11 digits long
  54. return phone;
  55. }

URL: http://andresgalindo.us/phone-formatting-in-javascript/

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.