Return to Snippet

Revision: 28877
at July 15, 2010 07:34 by agalindo


Initial Code
/** 
* Ported by Andres Galindo (http://andresgalindo.us)
* Shameless port of http://www.danielkassner.com/2010/05/21/format-us-phone-number-using-php
**/
function format_phone (phone, convert, trim){
    if( typeof convert == 'undefined' ){
        convert = true;
    }
    
    if( typeof trim == 'undefined' ){
        trim = true;
    }
        	
   	// Strip out any extra characters that we do not need only keep letters and numbers
   	phone = phone.replace(/[^0-9A-Za-z]/, "");
        	
   	// Do we want to convert phone numbers with letters to their number equivalent?
   	if ( convert == true && phone.match(/[a-zA-Z]/) ) {
  		var replace = {
            '2': ['a','b','c'],
            '3': ['d','e','f'],
            '4': ['g','h','i'],
            '5': ['j','k','l'],
            '6': ['m','n','o'],
            '7': ['p','q','r','s'],
            '8': ['t','u','v'],								 
            '9': ['w','x','y','z']
        }
        		
  		// Replace each letter with a number
  		// Notice this is case insensitive with the str_ireplace instead of str_replace 
  		for( digit in replace ){
  		    var regex = new RegExp('[' + replace[digit].join('') + ']', 'ig');
            phone = phone.replace(regex, digit);
  		}
   	}
        	
    // If we have a number longer than 11 digits cut the string down to only 11
   	// This is also only ran if we want to limit only to 11 characters
   	if( trim == true && phone.length > 11 ) {
        phone = phone.substr(0, 11);
   	}						 
        	
   	// Perform phone number formatting here
   	if( phone.length == 7 ) {
        return phone.replace(/([0-9a-zA-Z]{3})([0-9a-zA-Z]{4})/, "$1-$2");
   	}else if( phone.length == 10 ) {
        return phone.replace(/([0-9a-zA-Z]{3})([0-9a-zA-Z]{3})([0-9a-zA-Z]{4})/, "($1) $2-$3");
   	}else if( phone.length == 11 ) {
        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");
   	}
        	
   	// Return original phone if not 7, 10 or 11 digits long
   	return phone;
}

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

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

Initial Title
Phone formatting in JS

Initial Tags


Initial Language
JavaScript