Return to Snippet

Revision: 57957
at June 17, 2012 06:54 by cpres


Initial Code
/**
 *  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;
    }
}

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

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

Initial Title
10 Digit String to Phone Format

Initial Tags
regex, phone, convert

Initial Language
JavaScript