Home > Back-end >  Use Regex for phone number [duplicate]
Use Regex for phone number [duplicate]

Time:09-22

I'm working on a Regex.

let phones = ['321-1234567',' 355 321 1234567','0103 1234500', '00 355 3211234567' ]

I want to have the following results:

3211234567
 3553211234567
 3551031234500
 3553211234567

I have implemented this:

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

Output:

3211234567
 3553211234567
 3551031234500
 3553553211234567 --->wrong , it should be:  3553211234567

and it works only for the three first elements of array, but it doesn't work for the last one (the case when we should replace those two zeros with ).

So, when the phone number starts with a zero, replace that first zero with 355, when it starts with 00, replace those two zeros with .

How can I do that using a Regex, or should I use conditions like if phone.startsWith()?

My question is not a duplication of: Format a phone number (get rid of empty spaces and replace the first digit if it's 0)

as the solution there doesn't take in consideration the case when the phone number starts with 00 355 .

CodePudding user response:

let phones = ['321-1234567',' 355 321 1234567','0103 1234500', '00 355 3211234567' ]

phones = phones.map(r => r
  .replace(/^00/,' ')
  .replace(/^0/,' 355')
  .replace(/[^ \d] /g, '')
)

console.log(phones)

CodePudding user response:

You can use

let phones = ['321-1234567',' 355 321 1234567','0103 1234500', '00 355 3211234567' ]
for (const phone of phones) {
  console.log(
      phone.replace(/^0{1,2}/, (x) => x=='00'?' ':' 355')
           .replace(/(?!^\ )\D/g, ''))
}

Details:

  • .replace(/^0{1,2}/, (x) => x=='00'?' ':' 355') - matches 00 or 0 at the start of string, and if the match is 00, replacement is , else, replacement is 355 (here, x stands for the whole match value and if ? then : else is a ternary operator)
  • .replace(/(?!^\ )\D/g, '') removes any non-digit if it is not at the start of string.

Regex details:

  • ^0{1,2} - ^ matches start of string and 0{1,2} matches one or two zero chars
  • (?!^\ )\D - (?!^\ ) is a negative lookahead that fails the match if the char immediately to the right is that is located at the start of the string (due to ^ anchor), and \D matches any char other than a digit.

CodePudding user response:

your only problem is in this line replace(/^0 /,' 355') replace this with replace(/^0 /,' ')

phones.forEach(phone => {
      phone = phone.replace(/^0 /,' ').replace(/[^ \d] /g, '')
      console.log(phone)
    })
  • Related