如何计算特定字符串在另一个字符串中出现的次数。例如,这就是我试图在Javascript中做的事情:

var temp = "This is a string.";
alert(temp.count("is")); //should output '2'

当前回答

我的解决方案:

var temp=“这是一个字符串。”;函数countOccurrences(str,value){var regExp=新regExp(值,“gi”);return(str.match(regExp)| |[]).length;}console.log(countOccurrences(temp,'is'));

其他回答

只需编码打高尔夫球丽贝卡·切尔诺夫的解决方案:-)

alert(("This is a string.".match(/is/g) || []).length);

你可以试试这个:

var theString=“这是一个字符串。”;console.log(String.split(“is”).length-1);

ES2020提供了一个新的MatchAll,它可能在这个特定的环境中使用。

这里我们创建了一个新的RegExp,请确保将“g”传递到函数中。

使用Array.from转换结果并计算长度,根据原始请求者所需的输出返回2。

let strToCheck=RegExp('is','g')let matchesReg=“这是一个字符串。”.matchAll(strToCheck)console.log(Array.from(matchesReg).length)//2

看到这篇帖子。

let str = 'As sly as a fox, as strong as an ox';

let target = 'as'; // let's look for it

let pos = 0;
while (true) {
  let foundPos = str.indexOf(target, pos);
  if (foundPos == -1) break;

  alert( `Found at ${foundPos}` );
  pos = foundPos + 1; // continue the search from the next position
}

相同的算法可以被布置得更短:

let str = "As sly as a fox, as strong as an ox";
let target = "as";

let pos = -1;
while ((pos = str.indexOf(target, pos + 1)) != -1) {
  alert( pos );
}

太老了,但我今天需要做这样的事情,只想事后检查一下。对我来说工作很快。

String.prototype.count = function(substr,start,overlap) {
    overlap = overlap || false;
    start = start || 0;

    var count = 0, 
        offset = overlap ? 1 : substr.length;

    while((start = this.indexOf(substr, start) + offset) !== (offset - 1))
        ++count;
    return count;
};