Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

70
Views
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 answers
Answer question

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 Report

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 Report

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!