Search code snippets, questions, articles...

Calculate the frequency of characters in a string using Javascript

If you want to check how many times a character in a string appeared then you can use below code. It will print the object of string letters with their occuring frequency value.
const str = 'CoNgratulations';

const letters = {};
for (let char of str.toLowerCase()) {
    letters[char] = letters[char] + 1 || 1;

Best JSON Validator, JSON Tree Viewer, JSON Beautifier at same place.

In the code snippet, there is string str which contains some characters in it. We have converted the string to lowecase so that it does now confuse with capital letters and return the right rest.

We are looping through the string characters and adding 1 in each iteration in the letters object.

Live Demo

Search Index Data (The code snippet can also be found with below search text)

Check how many times a character appeared in a string Javascript
Was this helpful?