gpt4 book ai didi

javascript - 用计数器升序替换所有特定字符?

转载 作者:行者123 更新时间:2023-11-30 08:33:03 25 4
gpt4 key购买 nike

我有这样一个字符串:

var str = "some text is here
- first case
- second case
- third case
some text is here";

现在我需要这个输出:

var newstr = "some text is here
1. first case
2. second case
3. third case
some text is here";

我能做的就是removing those - .现在我需要用动态数字替换 $1...这可能吗?

像这样:

.replace (/(^\s*-\s+)/gm, "{A dynamic number which is ascending}. ")

最佳答案

您可以使用 String#replace带有回调和计数器。

使用 ES2015 Arrow function :

str.replace(/^\s*- /gm, () => counter++ + '. ');

var str = `some text is here
- first case
- second case
- third case
some text is here`;

var counter = 1;
str = str.replace(/^\s*- /gm, () => counter++ + '. ');

console.log(str);
document.write(str); // Demo purpose

ES5 中的等效代码

str.replace(/^\s*- /gm, function() {
return counter++ + '. ';
});

正则表达式 /^\s*-/gm 将匹配所有以任意数量的空格开头后跟连字符的行。

var str = `some text is here
- first case
- second case
- third case
some text is here`;

var counter = 1; // Initialize the counter

str = str.replace(/^\s*- /gm, function() {
return counter++ + '. '; // Incrementing counter after using its value
});

console.log(str);
document.write(str); // Demo purpose

关于javascript - 用计数器升序替换所有特定字符?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35059666/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com