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

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

当前回答

var str=“堆栈流”;var arr=Array.from(str);控制台日志(arr);for(设a=0;a<=arr.length;a++){变量温度=arr[a];变量c=0;for(设b=0;b<=arr.length;b++){如果(温度==arr[b]){c++;}}console.log(“${arr[a]}计入${c}”)}

其他回答

var countInstances=函数(主体,目标){var全局计数器=0;var concatstring=“”;for(var i=0,j=target.length;i<body.length;i++){concatstring=body.substring(i-1,j);if(concatstring===目标){全局计数器+=1;concatstring='';}}返回全局计数器;};console.log(countInstance('abcabc','abc'));//==>2.console.log(countInstance('ababa','aba'));//==>2.console.log(countInstance('aaabbb','ab'));//==>1.

非正则表达式版本:

var string='这是一个字符串',searchFor='is',计数=0,pos=string.indexOf(searchFor);而(位置>-1){++计数;pos=string.indexOf(searchFor,++pos);}console.log(计数);//2.

您可以使用match来定义这样的函数:

String.prototype.count = function(search) {
    var m = this.match(new RegExp(search.toString().replace(/(?=[.\\+*?[^\]$(){}\|])/g, "\\"), "g"));
    return m ? m.length:0;
}

Leandro Batista的答案:只是正则表达式有问题。

“使用严格”;var dataFromDB=“testal”;$('input[name=“tbInput”]').on(“change”,function(){var charToTest=$(this).val();var howManyChars=charToTest.length;var nrMatches=0;如果(howManyChars!==0){charToTest=charToTest.charAt(0);var regexp=新regexp(charToTest,'gi');var arrMatches=dataFromDB.match(正则表达式);nrMatches=arrMatches?arrMatches.length:0;}$('#result').html(nrMatches.toString());});<script src=“https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js“></script><div class=“main”>你想数什么<input type=“text”name=“tbInput”value=“”><br/>出现次数=<span id=“result”>0</span></div>

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

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;
};