-4

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.

Weronika
  • 370
  • 1
  • 4
  • 16

2 Answers2

2

FYI - string.replace() will only replace the first instance of whatever you want to replace whereas string.replaceAll() will replace all instances.

Mahyar Mottaghi Zadeh
  • 1,178
  • 6
  • 18
  • 31
1

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);
Tim Biegeleisen
  • 502,043
  • 27
  • 286
  • 360