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\";
s = 'dir/dir/dir/dir/'
for(i=l=0;i<s.length;i++)
if(s[i] == '/')
l++
I was working on a small project that required a sub-string counter. Searching for the wrong phrases provided me with no results, however after writing my own implementation I have stumbled upon this question. Anyway, here is my way, it is probably slower than most here but might be helpful to someone:
function count_letters() {
var counter = 0;
for (var i = 0; i < input.length; i++) {
var index_of_sub = input.indexOf(input_letter, i);
if (index_of_sub > -1) {
counter++;
i = index_of_sub;
}
}
http://jsfiddle.net/5ZzHt/1/
Please let me know if you find this implementation to fail or do not follow some standards! :)
UPDATE You may want to substitute:
for (var i = 0; i < input.length; i++) {
With:
for (var i = 0, input_length = input.length; i < input_length; i++) {
Interesting read discussing the above: http://www.erichynds.com/blog/javascript-length-property-is-a-stored-value
I have found that the best approach to search for a character in a very large string (that is 1 000 000 characters long, for example) is to use the replace()
method.
window.count_replace = function (str, schar) {
return str.length - str.replace(RegExp(schar), '').length;
};
You can see yet another JSPerf suite to test this method along with other methods of finding a character in a string.
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;
var a = "acvbasbb";
var b= {};
for (let i=0;i<a.length;i++){
if((a.match(new RegExp(a[i], "g"))).length > 1){
b[a[i]]=(a.match(new RegExp(a[i], "g"))).length;
}
}
console.log(b);
In javascript you can use above code to get occurrence of a character in a string.
If you are using lodash, the _.countBy method will do this:
_.countBy("abcda")['a'] //2
This method also work with array:
_.countBy(['ab', 'cd', 'ab'])['ab'] //2