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

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

当前回答

非正则表达式版本:

var string='这是一个字符串',searchFor='is',计数=0,pos=string.indexOf(searchFor);而(位置>-1){++计数;pos=string.indexOf(searchFor,++pos);}console.log(计数);//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(),因为它消耗更少的资源!我的回答只是为了好玩,并表明解决这个问题有很多可能性

参数:ustring:超集字符串countChar:子字符串

一个计算JavaScript中子字符串出现次数的函数:

函数subStringCount(ustring,countChar){var correspCount=0;var corresp=false;变量量=0;var prevChar=空;对于(var i=0;i!=ustring.length;i++){如果(ustring.charAt(i)==countChar.charAt(0)&&corresp==false){corresp=真;correspCount+=1;如果(correspCount==countChar.length){数量+=1;corresp=false;correspCount=0;}prevChar=1;}否则如果(ustring.charAt(i)==countChar.charAt(prevChar)&&corresp==true){correspCount+=1;如果(correspCount==countChar.length){数量+=1;corresp=false;correspCount=0;prevChar=空;}其他{prevChar+=1;}}其他{corresp=false;correspCount=0;}} 回报金额;}console.log(subStringCount(“Hello World,Hello World”,“ll”));

添加了此优化:

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

这可能是这里最快的实现,但如果您将“++pos”替换为“pos+=searchFor.length”,则会更快汉森里克

function occurrences(str_, subStr) {
  let occurence_count = 0
  let pos = -subStr.length
  while ((pos = str_.indexOf(subStr, pos + subStr.length)) > -1) {
    occurence_count++
  }
  return occurence_count
}

正则表达式(global的缩写)中的g表示搜索整个字符串,而不仅仅是查找第一个出现的字符串。此匹配是两次:

var temp=“这是一个字符串。”;var count=(temp.match(/is/g)| |[]).length;console.log(计数);

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

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

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