'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"
Solution 1:[1]
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"))
Solution 2:[2]
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);
Solution 3:[3]
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('-'))
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Amadan |
| Solution 2 | Giorgio Polvara - Gpx |
| Solution 3 | Rohìt JÃndal |
