-2

I have a string with a number:

const phoneNo = '2321392321';

and I want it to have this formt: (999) 999 - 9999.

Is it possible to do it with regex? I could split the number, take a substring, etc, but I feel like it'd be easier with regex, though I don't know how to tackle it.

Ivar
  • 6,138
  • 12
  • 49
  • 61
nick
  • 2,819
  • 5
  • 33
  • 69

1 Answers1

1

Here is an example:

const phoneNo = '2321392321';

const formatted = phoneNo.replace(/(\d{3})(\d{3})(\d{4})/, '($1) $2 - $3')

console.log(formatted)

In the regex, we are capturing the digits into 3 separate groups and then we are back-referencing them inside .replace using $1, $2 and $3

Tibebes. M
  • 6,940
  • 5
  • 15
  • 36