Format Phone Number

/**
 * @description - function that takes 10 digits and returns a string of the formatted phone number e.g.: 1234567890 -> (123) 456-7890
 * @param {string} phoneNumber
 * @returns {string} - Format to (XXX) XXX-XXXX pattern
 */
const formatPhoneNumber = (phoneNumber) => {
  if ((phoneNumber.length !== 10) || isNaN(phoneNumber)) {
    // return "Invalid phone number."
    throw new TypeError('Invalid phone number!')
  }

  let index = 0
  return '(XXX) XXX-XXXX'.replace(/X/g, () => phoneNumber[index++])
}

export default formatPhoneNumber
Algerlogo

Β© Alger 2022

About us

We are a group of programmers helping each other build new things, whether it be writing complex encryption programs, or simple ciphers. Our goal is to work together to document and model beautiful, helpful and interesting algorithms using code. We are an open-source community - anyone can contribute. We check each other's work, communicate and collaborate to solve problems. We strive to be welcoming, respectful, yet make sure that our code follows the latest programming guidelines.