简体   繁体   中英

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.

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM