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

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

当前回答

这是我2022年使用map()和filter()的解决方案:

string = "Xanthous: A person with yellow hair. Her hair was very xanthous in colour."       
count = string.split('').map((e,i) => { if(e === 'e') return i;}).filter(Boolean).length

只是为了使用这些功能的乐趣。该示例计算字符串中“e”的数量。

这与使用match()函数相同:

(string.match(/e/g)||[]).length

或者简单地使用split()函数:

string.split('e').length - 1

我认为最好的方法是使用match(),因为它消耗更少的资源!我的回答只是为了好玩,并表明解决这个问题有很多可能性

其他回答

       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字符串中出现的子字符串,以了解分步说明。

 function substrCount( str, x ) {
   let count = -1, pos = 0;
   do {
     pos = str.indexOf( x, pos ) + 1;
     count++;
   } while( pos > 0 );
   return count;
 }

只需编码打高尔夫球丽贝卡·切尔诺夫的解决方案:-)

alert(("This is a string.".match(/is/g) || []).length);

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

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

现在这是我遇到的一个非常古老的线索,但随着许多人推送他们的答案,这里是我的,希望能帮助一些人使用这个简单的代码。

var search_value=“这是一个假句子!”;var letter='a'/*可以接受任何字母,如果任何人想动态使用此变量,请输入一个var*/letter=letter&&“string”===字母类型?字母:“”;变量计数;对于(var i=count=0;i<search_value.length;count+=(search_value[i++]==字母));console.log(计数);

我不确定它是否是最快的解决方案,但我更喜欢它,因为它简单且不使用正则表达式(我只是不喜欢使用它们!)