Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

318
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda