gpt4 book ai didi

javascript将子字符串替换为重复次数的值

转载 作者:行者123 更新时间:2023-11-28 15:55:11 25 4
gpt4 key购买 nike

我在给这个问题赋予适当的标题时遇到了一些困难。下面是我想要的示例。

var originalString ="hello all, This is a hello string written by hello";
var substringToBeCounted = "hello";
var expectedString ="1 hello all, This is a 2 hello string written by 3 hello; .

我正在尝试在整个字符串中附加“hello”实例的计数。

这是我迄今为止得到的工作解决方案:

   var hitCount = 1;
var magicString = "ThisStringWillNeverBePresentInOriginalString";
while(originalString .match(substringToBeCounted ).length >0){

originalString = originalString .replace(substringToBeCounted , hitCount + magicString );
hitCount++;
}

var re = new RegExp(magicString,'gi');

originalString = originalString.replace(re, subStringToBeCounted);

为了解释上面的代码:我正在循环直到匹配在原始字符串中找到“hello”,并且在循环中我将 hello 更改为具有我想要的计数的一些奇怪的字符串。

最后我将奇怪的字符串替换回 hello。

这个解决方案对我来说看起来很老套。

有没有什么聪明的解决方案来解决这个问题。

谢谢

最佳答案

Replace 接受一个函数作为替换;这样你就可以返回你想要的内容

var originalString = "hello all, This is a hello string written by hello";
var substringToBeCounted = "hello";

var count = 0;
var reg = new RegExp(substringToBeCounted, 'g');
// this could have just been /hello/g if it isn't dynamically created

var replacement = originalString.replace(reg, function(found) {
// hint: second function parameter is the found index/position
count++;
return count + ' ' + found;
});

为了使其更可重用:

function counterThingy(haystack, needle) {
var count = 0;
var reg = new RegExp(needle, 'g');

return haystack.replace(reg, function(found) {
count++;
return count + ' ' + found;
});
}

var whatever = counterThingy(originalString, substringToBeCounted);

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replace

关于javascript将子字符串替换为重复次数的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19190569/

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