添加另一个字符串时的JavaScript子字符串无法正常工作

发布于 2025-01-23 21:19:41 字数 405 浏览 1 评论 0 原文

有人可以帮助我在下面检查此代码,并告诉我我做错了什么。

预期结果

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

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"

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

貪欢 2025-01-30 21:19:41

用字符串目标替换将找到并替换目标的第一次出现。 2 2022-04-2 中的第一次出现在这里:

2022-04-2
^

而不是在这里:

2022-04-2
        ^

要执行您想做的事情,使用索引,请勿使用 replace

const str = '2022-04-2';

console.log(str.substring(0, 8) + "0" + str.substring(8));

或者,如果您确实使用目标,请更加精确:

const str = '2022-04-2';

console.log(str.replace(/\b(\d)\b/g, "0$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"))

有深☉意 2025-01-30 21:19:41

这是因为替换无法正常工作。在代码中,您编写的IT搜索了字符串“ 2” 的第一次出现,并用“ 02” 替换它。在您的情况下,“ 2022-04-02” 第一个“ 2” 是第一个字符。

我建议一种不同的方法:

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

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);
心房敞 2025-01-30 21:19:41

您只需使用方法。

演示

const str = '2022-04-2';

const splittedStr = str.split('-');

splittedStr[2] = '0' + splittedStr[2]

console.log(splittedStr.join('-'))

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('-'))

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文