How To Format A Phone Number In Javascript

How To Format A Phone Number In Javascript

Javascript and Jquery are two of the most common tools we use to format phone numbers.

Learn how to format a phone number in javascript properly.

Example

Input:
9809142333

Output:
(980) 914-2333

Format Phone Number Without Country Code

A phone number must be numeric and not longer than 10 digits in order to be properly formatted.

As soon as we have all of our data, we can begin formatting it in US phone mode.

let formatPhoneNumber = (str) => {
  //Filter only numbers from the input
  let cleaned = ('' + str).replace(/\D/g, '');

  //Check if the input is of correct length
  let match = cleaned.match(/^(\d{3})(\d{3})(\d{4})$/);

  if (match) {
    return '(' + match[1] + ') ' + match[2] + '-' + match[3]
  };

  return null
};
Input:
console.log(formatPhoneNumber('9809142333'));
console.log(formatPhoneNumber('98091sss42333'));

Output:
"(980) 914-2333"
"(980) 914-2333"

Without the nation extension code, this will operate perfectly. However, if you want to format phone numbers with national extension codes, you’ll need to make some changes to the method.

Format Phone Number With Country Code

let formatPhoneNumber = (str) => {
  //Filter only numbers from the input
  let cleaned = ('' + str).replace(/\D/g, '');

  //Check if the input is of correct
  let match = cleaned.match(/^(1|)?(\d{3})(\d{3})(\d{4})$/);

  if (match) {
    //Remove the matched extension code
    //Change this to format for any country code.
    let intlCode = (match[1] ? '+1 ' : '')
    return [intlCode, '(', match[2], ') ', match[3], '-', match[4]].join('')
  }

  return null;
}
Input:
console.log(formatPhoneNumber('9809142333'));
console.log(formatPhoneNumber('+19801542335'));

Output:
"(980) 914-2333"
"+1 (980) 154-2335"