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

var temp = "This is a string.";
alert(temp.count("is")); //should output '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;
}

其他回答

我们可以使用jssplit函数,它的长度减1就是出现的次数。

var temp = "This is a string.";
alert(temp.split('is').length-1);

看到这篇帖子。

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 );
}
var mystring = 'This is the lorel ipsum text';
var mycharArray = mystring.split('');
var opArr = [];
for(let i=0;i<mycharArray.length;i++){
if(mycharArray[i]=='i'){//match the character you want to match
    opArr.push(i);
  }}
console.log(opArr); // it will return matching index position
console.log(opArr.length); // it will return length

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

const countOccurence = (string, char) => {
const chars = string.match(new RegExp(char, 'g')).length
return chars;
}

参数: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”));