Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

316
Visualizações
Format a phone number (get rid of empty spaces and replace the first digit if it's 0)

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.

about 4 years ago · Juan Pablo Isaza
3 Respostas
Responde à pergunta

0

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

about 4 years ago · Juan Pablo Isaza Relatório

0

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

about 4 years ago · Juan Pablo Isaza Relatório

0

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
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda