添加另一个字符串时的JavaScript子字符串无法正常工作
有人可以帮助我在下面检查此代码,并告诉我我做错了什么。
预期结果
'2022-04-02'
输出结果
"02022-04-2"
代码
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"
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
用字符串目标替换
将找到并替换目标的第一次出现。2
在2022-04-2
中的第一次出现在这里:而不是在这里:
要执行您想做的事情,使用索引,请勿使用
replace
:或者,如果您确实使用目标,请更加精确:
replace
with a string target will find and replace the first occurrence of the target. The first occurence of2
in2022-04-2
is here:and not here:
To do what you want, work with indices, don't use
replace
:Or be more precise about your targetting, if you do use it:
这是因为
替换
无法正常工作。在代码中,您编写的IT搜索了字符串“ 2”
的第一次出现,并用“ 02”
替换它。在您的情况下,“ 2022-04-02”
第一个“ 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:
您只需使用方法。
演示:
You can simply achieve it by using string.split() method.
Demo :