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

203
Vistas
JavaScript: Insert a character after every N characters

I have a string, which always has a lenght of 32:

var str = "34v188d9cefa401f988563fb153xy04b";

Now I need to add a minus (-) after following number of characters:

  • First minus after 8th character
  • Second minus after 12th character
  • Third minus after 16th character
  • Fourth minus after 20th character

Output should be:

34v188d9-cefa-401f-9885-63fb153xy04b

So far I have tried different calculations with e.g.:

str.split('').reduce((a, b, c) => a + b + (c % 6 === 4 ? '-' : ''), '');

But I don't get the expected result.

about 4 years ago · Juan Pablo Isaza
3 Respuestas
Responde la pregunta

0

You could use a regex replacement:

var str = "34v188d9cefa401f988563fb153xy04b";
var output = str.replace(/^(.{8})(.{4})(.{4})(.{4})(.{12})$/, "$1-$2-$3-$4-$5");
console.log(output);

about 4 years ago · Juan Pablo Isaza Denunciar

0

If you want to use reduce you can do something like this

var str = "34v188d9cefa401f988563fb153xy04b";


const result = str.split('').reduce((res, c, i) => {
  const hiphensPositions = [7, 11, 15, 19]
  return res + c + (hiphensPositions.includes(i)?'-':'')
}, '')

console.log(result)

about 4 years ago · Juan Pablo Isaza Denunciar

0

     var str = "34v188d9cefa401f988563fb153xy04b";
     var a="" 
     for (let i in str){if (i == 7 || i==11 ||  i==15  ||  i == 
      19){a = a+str[i]+"-"} else{a+=str[i] }}

should do it.

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