0

我在给这个问题赋予适当的标题时有点困难。下面是我想要的一个例子。

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。

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

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

谢谢

4

1 回答 1

4

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

于 2013-10-04T20:56:23.897 回答