format phone number javascript code example

Example 1: javascript function to format phone number

function formatPhoneNumber(phoneNumberString) {
  var cleaned = ('' + phoneNumberString).replace(/\D/g, '')
  var match = cleaned.match(/^(\d{3})(\d{3})(\d{4})$/)
  if (match) {
    return '(' + match[1] + ') ' + match[2] + '-' + match[3]
  }
  return null
}

Example 2: phone number formatter javascript grepper

// Checks if a string is a valid americain phone number

var phoneFormatter = function(phoneNumber) {
    var counter;
    var current;
    var phoneNumberLength = phoneNumber.length;
    var digits = ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9"];
    var delimiter = "-";
    
    if( typeof phoneNumber !== "string" || phoneNumberLength !== 8) return false;
    for(counter = 0; counter < phoneNumberLength; counter++) {
        current = phoneNumber[counter];
        if(digits.indexOf(current) === -1) {
            if (phoneNumber[3] === delimiter) {
                return true;
            } else if(current !== delimiter) {
                return false;
            }
        }
    }   
    
    return true;
}