Home > Software design >  Format a phone number (get rid of empty spaces and replace the first digit if it's 0)
Format a phone number (get rid of empty spaces and replace the first digit if it's 0)

Time:09-16

I have a phone number (phone) which will be sent to an API endpoint via a PUT request. Before sending to the API, I want to format it.

Cases:

1)

Phone number: 0321 1234567
Send to API like:  3553211234567
Phone Number:  355 321 1234567
Send to API like:  3553211234567
Phone Number:  3553211234567
Send to API like:  3553211234567

So, what I need to do is:

1- remove empty spaces

for this I'm using:

phone.replace(/[^ \d] /g, "") 

remove everything except (for country codes) and digits.

2- check if the phone number starts with 0. If true, replace it with 355.

How can I do this in Javascript? Thank you in advance.

CodePudding user response:

I probably went with a too difficult solution here, but what about matching the last 10 digits and join those back together:

const str = ' 355 321 1234567';
const array = [...str.matchAll(/\d(?!(?:.*\d){10})/g)];
console.log(' 355'   array.join(''));

CodePudding user response:

You can use two replaces, one for 0 to 355 and one for spaces. To get just the first 0 use ^0 which will match only if the very first character is 0.

let phones = ['0321 1234567',' 355 321 1234567',' 3553211234567', '0103 1234500']

phones.forEach(phone => {
  phone = phone.replace(/^0/,' 355')
  phone = phone.replace(/\s/g,'')
  console.log(phone)
})

CodePudding user response:

You could also use a callback function with replace and capture the zero at the start in group 1, or match 1 or more whitespace chars using (^0)|\s

In the callback check for group 1. If it is there, add 355, else an empty string.

Example code

let regex = /(^0)|\s /g;
[
"0321 1234567",
" 355 321 1234567",
" 3553211234567"
].forEach( s => 
console.log(
s.replace(regex, (m, g1) => g1 ? " 355" : ""))
);

Output for all 3

 3553211234567
  • Related