Matt K Matt K - 3 months ago 7
Javascript Question

Regular Expression to reformat a US phone number in Javascript

I'm looking to reformat (replace, not validate - there are many references for validating) a phone number for display in Javascript. Here's an example of some of the data:


  • 123 4567890

  • (123) 456-7890

  • (123)456-7890

  • 123 456 7890

  • 123.456.7890

  • (blank/null)

  • 1234567890



Is there an easy way to use a regular expression to do this? I'm looking for the best way to do this. Is there a better way?

I want to reformat the number to the following:
(123) 456-7890

Answer

Assuming you want the format "(123) 456-7890":

function formatPhoneNumber(s) {
  var s2 = (""+s).replace(/\D/g, '');
  var m = s2.match(/^(\d{3})(\d{3})(\d{4})$/);
  return (!m) ? null : "(" + m[1] + ") " + m[2] + "-" + m[3];
}