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

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

当前回答

一种简单的方法是将字符串拆分为所需单词,即我们要计算出现次数的单词,然后从部分数中减去1:

function checkOccurences(string, word) {
      return string.split(word).length - 1;
}
const text="Let us see. see above, see below, see forward, see backward, see left, see right until we will be right"; 
const count=countOccurences(text,"see "); // 2

其他回答

试试看:

function countString(str, search){
    var count=0;
    var index=str.indexOf(search);
    while(index!=-1){
        count++;
        index=str.indexOf(search,index+1);
    }
    return count;
}
//Try this code

const countSubStr = (str, search) => {
    let arrStr = str.split('');
    let i = 0, count = 0;

    while(i < arrStr.length){
        let subStr = i + search.length + 1 <= arrStr.length ?
                  arrStr.slice(i, i+search.length).join('') :
                  arrStr.slice(i).join('');
        if(subStr === search){
            count++;
            arrStr.splice(i, search.length);
        }else{
            i++;
        }
    }
    return count;
  }

参数:ustring:超集字符串countChar:子字符串

一个计算JavaScript中子字符串出现次数的函数:

函数subStringCount(ustring,countChar){var correspCount=0;var corresp=false;变量量=0;var prevChar=空;对于(var i=0;i!=ustring.length;i++){如果(ustring.charAt(i)==countChar.charAt(0)&&corresp==false){corresp=真;correspCount+=1;如果(correspCount==countChar.length){数量+=1;corresp=false;correspCount=0;}prevChar=1;}否则如果(ustring.charAt(i)==countChar.charAt(prevChar)&&corresp==true){correspCount+=1;如果(correspCount==countChar.length){数量+=1;corresp=false;correspCount=0;prevChar=空;}其他{prevChar+=1;}}其他{corresp=false;correspCount=0;}} 回报金额;}console.log(subStringCount(“Hello World,Hello World”,“ll”));

这是我的解决方案。我希望这会对某人有所帮助

const countOccurence = (string, char) => {
const chars = string.match(new RegExp(char, 'g')).length
return chars;
}
 function substrCount( str, x ) {
   let count = -1, pos = 0;
   do {
     pos = str.indexOf( x, pos ) + 1;
     count++;
   } while( pos > 0 );
   return count;
 }