Count the number of occurrences of a character in a string in Javascript

后端 未结 30 2541
礼貌的吻别
礼貌的吻别 2020-11-22 02:33

I need to count the number of occurrences of a character in a string.

For example, suppose my string contains:

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


        
30条回答
  •  旧时难觅i
    2020-11-22 03:17

    The fifth method in Leo Sauers answer fails, if the character is on the beginning of the string. e.g.

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

    will give 2 instead of 3, because the filter funtion Boolean gives false for 0.

    Other possible filter function:

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

提交回复
热议问题