我对这个问题给予正确的标题有点困难。以下是我想要的一个例子。
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更改为一些奇怪的字符串以及我想要的计数。
最后我将奇怪的字符串替换回你好。
这个解决方案对我来说非常讨厌。
是否有任何聪明的解决方案可以解决这个问题。
由于
答案 0 :(得分:4)
替换接受函数作为替换;这样你可以返回你想要的东西
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