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\";
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;