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

javascript to replace a substring with value of how many times it is repeated

本文关键字:字符串 替换 JavaScript      更新时间:2023-09-26

我在给这个问题起正确的标题时遇到了一点困难。下面是我想要的示例。

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

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

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

这个解决方案对我来说看起来很笨拙。

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

谢谢

替换接受函数作为替换;这样你就可以返回你想要的东西

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