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

73
Vistas
JavaScript substring not working as expected when adding another string

Can someone help me check this code below and tell me what I'm doing wrong.

Expected result

'2022-04-02'

Output result

"02022-04-2"

code

const str = '2022-04-2';

console.log(str.substring(8));


console.log(str.replace(str.substring(8, 9), "0" + str.substring(8,9)));
// expected output: "2022-04-02"

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

0

replace with a string target will find and replace the first occurrence of the target. The first occurence of 2 in 2022-04-2 is here:

2022-04-2
^

and not here:

2022-04-2
        ^

To do what you want, work with indices, don't use replace:

const str = '2022-04-2';

console.log(str.substring(0, 8) + "0" + str.substring(8));

Or be more precise about your targetting, if you do use it:

const str = '2022-04-2';

console.log(str.replace(/\b(\d)\b/g, "0$1"))

about 4 years ago · Juan Pablo Isaza Denunciar

0

It's because replace doesn't work as you think. In the code you wrote it searches for the first occurrence of the string "2" and it replaces it with "02". In your case for "2022-04-02" the first "2" is the very first character.

I suggest a different approach:

const str = "2022-04-2";
const [year, month, day] = str.split("-");
const formattedDate = `${year}-${month.padStart(2, "0")}-${day.padStart(2, "0")}`;
console.log(formattedDate);
about 4 years ago · Juan Pablo Isaza Denunciar

0

You can simply achieve it by using string.split() method.

Demo :

const str = '2022-04-2';

const splittedStr = str.split('-');

splittedStr[2] = '0' + splittedStr[2]

console.log(splittedStr.join('-'))

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