How to count string occurrence in string?

2018-12-31 06:10发布

How can I count the number of times a particular string occurs in another string. For example, this is what I am trying to do in Javascript:

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

25条回答
牵手、夕阳
2楼-- · 2018-12-31 06:38

function get_occurrence(varS,string){//Find All Occurrences
        c=(string.split(varS).length - 1);
        return c;
    }
    temp="This is a string.";
    console.log("Total Occurrence is "+get_occurrence("is",temp));

Use get_occurrence(varS,string) to find occurrence of both characters and string in a String.

查看更多
只若初见
3楼-- · 2018-12-31 06:42

You can use match to define such function:

String.prototype.count = function(search) {
    var m = this.match(new RegExp(search.toString().replace(/(?=[.\\+*?[^\]$(){}\|])/g, "\\"), "g"));
    return m ? m.length:0;
}
查看更多
刘海飞了
4楼-- · 2018-12-31 06:42

var s = "1";replaced word
var a = "HRA"; //have to replace 
var str = document.getElementById("test").innerHTML;
var count = str.split(a).length - 1;
for (var i = 0; i < count; i++) {
    var s = "1";
    var a = "HRA";
    var str = document.getElementById("test").innerHTML;
    var res = str.replace(a, s);
    document.getElementById("test").innerHTML = res;
}

<input " type="button" id="Btn_Validate" value="Validate" class="btn btn-info" />
<div class="textarea"  id="test" contenteditable="true">HRABHRA</div>

查看更多
梦醉为红颜
5楼-- · 2018-12-31 06:43

The non-regex version:

 var string = 'This is a string',
    searchFor = 'is',
    count = 0,
    pos = string.indexOf(searchFor);

while (pos > -1) {
    ++count;
    pos = string.indexOf(searchFor, ++pos);
}

console.log(count);   // 2

查看更多
呛了眼睛熬了心
6楼-- · 2018-12-31 06:43

Try it

<?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>
查看更多
孤独总比滥情好
7楼-- · 2018-12-31 06:44

Just code-golfing Rebecca Chernoff's solution :-)

alert(("This is a string.".match(/is/g) || []).length);
查看更多
登录 后发表回答