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

133
Vistas
Add a colon after two characters without using String.replace

I am currently using replace to insert a colon after the second character of a four-character string (1000). I think it is an elegant solution. But I wonder if there are any other elegant solutions for this? Thanks for your ideas!

Working code

const myStr = "1000";
const string = myStr.replace(/(\d{2})(\d{2})/g, '$1:$2');
console.log(string);

about 4 years ago · Santiago Gelvez
3 Respuestas
Responde la pregunta

0

You could stil take a regular expression which works for any time length, like four or six digits with colon for each group of two.

const 
    format = s => s.replace(/.(?=(..)+$)/g, '$&:');
    
console.log(format('1000'));
console.log(format('100000'));

about 4 years ago · Santiago Gelvez Denunciar

0

Keep it simple. Use string functions to manipulate strings:

const s1 = "1000";
const s2 = s1.slice(0, 2) + ":" + s1.slice(2);
console.log(s2);

about 4 years ago · Santiago Gelvez Denunciar

0

Definitely not the best way to do that, i'm just wondering how many alternatives there are

[...'1000'].map((c, i) => i !== 0 && i % 2 === 0 ? `:${c}` : c).join('') //10:00
[...'100000'].map((c, i) => i !== 0 && i % 2 === 0 ? `:${c}` : c).join('') //10:00:00
[...'10000000'].map((c, i) => i !== 0 && i % 2 === 0 ? `:${c}` : c).join('') //10:00:00:00
about 4 years ago · Santiago Gelvez 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