Skip to content
Advertisement

Format phone number in Javascript

I need to format phone number for example by replace():

From: +48 XX XXX XX XX where X is a number.

Example: +48 12 345 67 89

To: +48 XXX XXX XXX

Example: +48 123 456 789


Edit:

My work:

  • First, I tried to remove the spaces in string: phone.replace(' ', '');:

Before: +48 12 312 31 23

After: +4812 312 31 23

Conclusion: Something is wrong because it only formatted the first space instead of everything.

  • I also tried to separate it into parts, based on other questions about regex:

phone.replace(/(d{3})(d{3})(d{3})(d{3})/gi, '$1 $2 $3 $4'); and

phone.replace(/(d{3})" "(d{3})" "(d{3})" "(d{3})/gi, '$1 $2 $3 $4');

and many other configurations like this.

Before: +48 12 312 31 23

After: +48 12 312 31 23

Conclusion: For sure, something is wrong, there is no change. The problem is with the regex.

Advertisement

Answer

You could use a regex replacement approach here:

var input = "+48 12 345 67 89";
var output = input.replace(/s+/g, "")
                  .replace(/^(+d{2})(d{3})(d{3})(d{3})$/, "$1 $2 $3 $4");
console.log(input + " => " + output);
Advertisement