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

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

当前回答

我认为regex的目的与indexOf有很大不同。indexOf只需查找某个字符串的出现,而在正则表达式中,您可以使用[a-Z]之类的通配符,这意味着它将查找单词中的任何大写字符,而无需说明实际字符。

例子:

var index=“This is a string”.indexOf(“is”);console.log(索引);var length=“This is a string”.match(/[a-z]/g).length;//其中[a-z]是正则表达式通配符,这就是为什么其速度较慢的原因console.log(长度);

其他回答

试试看:

function countString(str, search){
    var count=0;
    var index=str.indexOf(search);
    while(index!=-1){
        count++;
        index=str.indexOf(search,index+1);
    }
    return count;
}
       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字符串中出现的子字符串,以了解分步说明。

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

试试看

<?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>

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.