Skip to main content

JavaScript function to format a phone number as "(123) 456-7891".

/**
 * Formats a phone number as "(123) 456-7891".
 *
 * Usage:
 * <input type="text" name="test" onblur="formatPhoneNumber(this);" />
 *
 * @link https://jsfiddle.net/kaleb/Dm4Jv/
 * @param {DOM:Input} phoneNumber
 */
function formatPhoneNumber(phoneNumber) {
    var numbers = phoneNumber.value.replace(/\D/g, ""),
        char = { 0: "(", 3: ") ", 6: "-" };
    phoneNumber.value = "";
    for (var i = 0; i < numbers.length; i++) {
        phoneNumber.value += (char[i] || "") + numbers[i];
    }
}

/**
 * Formats a phone number as "(123) 456-7891".
 *
 * @param {String} phoneNumber
 * @return {String} The formatted phone number.
 */
function formatPhoneNumber(phoneNumber) {
    var formattedPhoneNumber = "",
        phoneNumberTemplate = { 0: "(", 3: ") ", 6: "-" },
        countryCode = "";

    if (typeof phoneNumber === "undefined" || phoneNumber == null) {
        return formattedPhoneNumber;
    }

    var numbersOnly = phoneNumber.replace(/\D/g, "");

    // check for country code... pluck it off and stash it for later:
    if (numbersOnly.length === 11) {
        countryCode = numbersOnly.substring(0, 1) + " ";
        numbersOnly = numbersOnly.substring(1);
    }

    if (numbersOnly.length === 7) {
        // phone number w/out area code... just add hyphen after first 3 digits
        phoneNumberTemplate = { 3: "-" };
    }

    for (var i = 0; i < numbersOnly.length; i++) {
        formattedPhoneNumber += (phoneNumberTemplate[i] || "") + numbersOnly[i];
    }

    return countryCode + formattedPhoneNumber;
}