-3

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
  • 5,377
  • 12
  • 50
  • 56
nick
  • 2,397
  • 4
  • 26
  • 46

1 Answers1

0

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
  • 5,841
  • 4
  • 12
  • 34