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

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

当前回答

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

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

其他回答

       var myString = "This is a string.";
        var foundAtPosition = 0;
        var Count = 0;
        while (foundAtPosition != -1)
        {
            foundAtPosition = myString.indexOf("is",foundAtPosition);
            if (foundAtPosition != -1)
            {
                Count++;
                foundAtPosition++;
            }
        }
        document.write("There are " + Count + " occurrences of the word IS");

请参阅:-count字符串中出现的子字符串,以了解分步说明。

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

alert(("This is a string.".match(/is/g) || []).length);
 function substrCount( str, x ) {
   let count = -1, pos = 0;
   do {
     pos = str.indexOf( x, pos ) + 1;
     count++;
   } while( pos > 0 );
   return count;
 }

第二次迭代次数较少(仅当子字符串的第一个字母匹配时),但循环仍使用2:

   function findSubstringOccurrences(str, word) {
        let occurrences = 0;
        for(let i=0; i<str.length; i++){
            if(word[0] === str[i]){ // to make it faster and iterate less
                for(let j=0; j<word.length; j++){
                    if(str[i+j] !== word[j]) break;
                    if(j === word.length - 1) occurrences++;
                }
            }
        }
        return occurrences;
    }
    
    console.log(findSubstringOccurrences("jdlfkfomgkdjfomglo", "omg"));

对于将来找到此线程的任何人,请注意,如果您对其进行概括,则接受的答案不会总是返回正确的值,因为它会阻塞正则表达式运算符,如$和。。这里有一个更好的版本,可以处理任何针头:

function occurrences (haystack, needle) {
  var _needle = needle
    .replace(/\[/g, '\\[')
    .replace(/\]/g, '\\]')
  return (
    haystack.match(new RegExp('[' + _needle + ']', 'g')) || []
  ).length
}