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

69
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 Relatório

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