javascriptregexreplaceformatphone-number

Format phone number in Javascript to format XX XXX XX XX


I need to format phone number for example:

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:

What I tried:

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.

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.


Solution

  • 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);