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

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

当前回答

试试看

<?php 
$str = "33,33,56,89,56,56";
echo substr_count($str, '56');
?>

<script type="text/javascript">
var temp = "33,33,56,89,56,56";
var count = temp.match(/56/g);  
alert(count.length);
</script>

其他回答

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

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

函数countInstance(字符串,单词){返回字符串.split(word).length-1;}console.log(countInstance(“This is a string”,“is”))

一种简单的方法是将字符串拆分为所需单词,即我们要计算出现次数的单词,然后从部分数中减去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
//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;
  }

非正则表达式版本:

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