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"
CodePudding user response:
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"))
CodePudding user response:
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);