我需要计算字符串中某个字符出现的次数。

例如,假设我的字符串包含:

var mainStr = "str1,str2,str3,str4";

我想求出逗号的个数,也就是3个字符。以及按逗号分隔后的单个字符串的计数,也就是4。

我还需要验证每个字符串,即str1或str2或str3或str4不应该超过,比如说,15个字符。


当前回答

将此函数添加到sting prototype:

String.prototype.count=function(c) { 
  var result = 0, i = 0;
  for(i;i<this.length;i++)if(this[i]==c)result++;
  return result;
};

用法:

console.log("strings".count("s")); //2

其他回答

我更新了这个答案。我更喜欢使用火柴的想法,但它更慢:

console.log((“str1,str2,str3,str4”.match(/,/g) ||[]).长度);日志 3 console.log((“str1,str2,str3,str4”.match(new RegExp(“str”, “g”)) ||[]).长度);日志 4

如果事先知道要搜索什么,可以使用正则表达式文字;如果不知道,可以使用RegExp构造函数,并传入g标志作为参数。

匹配结果为空,因此|| []

以下是我在2009年给出的原始答案。它创建了一个不必要的数组,但是使用分割更快(截至2014年9月)。我很矛盾,如果我真的需要速度,毫无疑问我会使用分拆,但我更喜欢使用匹配。

旧答案(2009年):

如果你在找逗号:

(mainStr.split(",").length - 1) //3

如果你在找str

(mainStr.split("str").length - 1) //4

在@Lo的回答和我自己的愚蠢的性能测试中,分裂在速度上领先,至少在Chrome中,但再次创建额外的数组似乎不理智。

有一个非常棘手的方法,但它是相反的:

const sampleStringText = "/john/dashboard/language";

假设上面的例子,为了计算正斜杠的数量,你可以这样做:

console.log( sampleStringText.split('/') - 1 );

所以我建议使用函数(TypeScript):

const counter = (sentence: string, char: string): number => sentence.split(char) - 1;

我的解决方案:

function countOcurrences(str, value){
   var regExp = new RegExp(value, "gi");
   return str.match(regExp) ? str.match(regExp).length : 0;  
}

我对接受的答案做了轻微的改进,它允许检查区分大小写/不区分大小写的匹配,并且是附加到字符串对象的方法:

String.prototype.count = function(lit, cis) {
    var m = this.toString().match(new RegExp(lit, ((cis) ? "gi" : "g")));
    return (m != null) ? m.length : 0;
}

Lit是要搜索的字符串(例如'ex'), cis是不区分大小写的,默认为false,它将允许选择不区分大小写的匹配。 要搜索字符串'I love StackOverflow.com'中的小写字母'o',你可以使用:

var amount_of_os = 'I love StackOverflow.com'.count('o');

Amount_of_os等于2。 如果我们再次使用不区分大小写的匹配来搜索相同的字符串,您将使用:

var amount_of_os = 'I love StackOverflow.com'.count('o', true);

这一次,amount_of_os将等于3,因为字符串中的大写O包含在搜索中。

下面是最简单的逻辑,很容易理解

  //Demo string with repeat char 
  let str = "Coffee"
  //Splitted the str into an char array for looping
  let strArr = str.split("")
  //This below is the final object which holds the result
  let obj = {};
  //This loop will count char (You can also use traditional one for loop)
  strArr.forEach((value,index)=>{
      //If the char exists in the object it will simple increase its value
      if(obj[value] != undefined)
      {
          obj[value] = parseInt(obj[value]) + 1;
      }//else it will add the new one with initializing 1
      else{
          obj[value] =1;
      }      
  });

  console.log("Char with Count:",JSON.stringify(obj)); //Char with Count:{"C":1,"o":1,"f":2,"e":2}