如何计算字符串中出现的字符串?

JavaScript

MandyJinJin

2020-03-12

如何计算特定字符串在另一个字符串中出现的次数。例如,这就是我要使用Javascript进行的操作:

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

第938篇《如何计算字符串中出现的字符串?》来自Winter(https://github.com/aiyld/aiyld.github.io)的站点

13个回答
前端Eva 2020.03.12

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>

Tom神无 2020.03.12

Try this:

function countString(str, search){
    var count=0;
    var index=str.indexOf(search);
    while(index!=-1){
        count++;
        index=str.indexOf(search,index+1);
    }
    return count;
}
泡芙飞云 2020.03.12

This function return the number of occurrences of a word in text.

Note we use toLowerCase to calculate the number of occurrences whatever the format (capital, uppercase ...) of the word and the text

wordCount(text, word) {
    if (!text || !word) {
      return 0;
    }
    text = text.toLowerCase();
    word = word.toLowerCase();
    return ( text.split( word ).length - 1 );
}
猴子村村 2020.03.12

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.

宝儿达蒙 2020.03.12
       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");

Refer :- count a substring appears in the string for step by step explanation.

老丝达蒙 2020.03.12

Super duper old, but I needed to do something like this today and only thought to check SO afterwards. Works pretty fast for me.

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;
};
番长猿阳光 2020.03.12

I think the purpose for regex is much different from indexOf. indexOf simply find the occurance of a certain string while in regex you can use wildcards like [A-Z] which means it will find any capital character in the word without stating the actual character.

Example:

 var index = "This is a string".indexOf("is");
 console.log(index);
 var length = "This is a string".match(/[a-z]/g).length;
 // where [a-z] is a regex wildcard expression thats why its slower
 console.log(length);

古一飞云 2020.03.12

var temp = "This is a string.";
console.log((temp.match(new RegExp("is", "g")) || []).length);

小胖Stafan 2020.03.12

String.prototype.Count = function (find) {
    return this.split(find).length - 1;
}

console.log("This is a string.".Count("is"));

This will return 2.

斯丁JinJin 2020.03.12
function countInstances(string, word) {
   return string.split(word).length - 1;
}
古一泡芙小卤蛋 2020.03.12

您可以尝试以下方法:

var theString = "This is a string.";
console.log(theString.split("is").length - 1);

Pro宝儿 2020.03.12

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;
}
梅老丝 2020.03.12

g正则表达式(简称全球)说,搜索整个字符串,而不是只要找到第一次出现。这匹配is两次:

var temp = "This is a string.";
var count = (temp.match(/is/g) || []).length;
console.log(count);

并且,如果没有匹配项,则返回0

var temp = "Hello World!";
var count = (temp.match(/is/g) || []).length;
console.log(count);

问题类别

JavaScript Ckeditor Python Webpack TypeScript Vue.js React.js ExpressJS KoaJS CSS Node.js HTML Django 单元测试 PHP Asp.net jQuery Bootstrap IOS Android