Skip to content

Get count of each character in a string using JavaScript

Advertisements
function charCount(str) {
var result = {};
str.replace(/\S/g, function(l){result[l] = (isNaN(result[l]) ? 1 : result[l] + 1);});
return result;
}

The function above returns an object with the count of each character in a string.

console.log(charCount("We poopcode!"));

/*
{!:1
W:1
c:1
d:1
e:2
o:3
p:2
}
*/
See also  HackerRank Solutions - Stacks - Balanced Brackets - Java Solution
, , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , ,

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.