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

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

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

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

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


当前回答

最简单的办法是…

的例子,

str = 'mississippi';

function find_occurences(str, char_to_count){
    return str.split(char_to_count).length - 1;
}

find_occurences(str, 'i') //outputs 4

其他回答

至少有五种方法。最好的选项,也应该是最快的(由于本机RegEx引擎)被放在顶部。

方法1

("this is foo bar".match(/o/g)||[]).length;
// returns 2

方法2

"this is foo bar".split("o").length - 1;
// returns 2

不建议拆分,因为它是资源饥渴的。它为每个匹配分配新的“Array”实例。不要通过FileReader尝试>100MB文件。你可以观察确切的资源使用使用Chrome的分析器选项。

方法3

    var stringsearch = "o"
       ,str = "this is foo bar";
    for(var count=-1,index=-2; index != -1; count++,index=str.indexOf(stringsearch,index+1) );
// returns 2

方法4

搜索单个字符

    var stringsearch = "o"
       ,str = "this is foo bar";
    for(var i=count=0; i<str.length; count+=+(stringsearch===str[i++]));
     // returns 2

方法5

元素映射和过滤。不建议这样做,因为它的整体资源预分配,而不是使用python的“生成器”:

    var str = "this is foo bar"
    str.split('').map( function(e,i){ if(e === 'o') return i;} )
                 .filter(Boolean)
    //>[9, 10]
    [9, 10].length
    // returns 2

分享: 我做了这个要点,目前有8种方法的字符计数,所以我们可以直接汇集和分享我们的想法-只是为了好玩,也许一些有趣的基准:)

快速搜索谷歌得到了这个(从http://www.codecodex.com/wiki/index.php?title=Count_the_number_of_occurrences_of_a_specific_character_in_a_string#JavaScript)

String.prototype.count=function(s1) { 
    return (this.length - this.replace(new RegExp(s1,"g"), '').length) / s1.length;
}

像这样使用它:

test = 'one,two,three,four'
commas = test.count(',') // returns 3

Leo Sauers回答中的第五种方法失败,如果字符位于字符串的开头。 如。

var needle ='A',
  haystack = 'AbcAbcAbc';

haystack.split('').map( function(e,i){ if(e === needle) return i;} )
  .filter(Boolean).length;

将给出2而不是3,因为过滤函数布尔为0给出false。

其他可能的过滤功能:

haystack.split('').map(function (e, i) {
  if (e === needle) return i;
}).filter(function (item) {
  return !isNaN(item);
}).length;

还有一个答案:

function count(string){
  const count={}
  
  string.split('').forEach(char=>{
    count[char] = count[char] ? (count[char]+1) : 1;
  })
  
  return count
}

console.log(count("abfsdfsddsfdfdsfdsfdsfda"))

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

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

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

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

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

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

那么string.split(desiredcharacter).length-1呢

例子:

Var STR = "hello is life"; Var len = str.split("h").length-1;将为上述字符串中的字符“h”提供计数2;