Chrome Extension

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;
}

console.log(letters);
Best JSON Validator, JSON Tree Viewer, JSON Beautifier at same place. Check how cool is the tool
Output
{"c":1,"o":2,"n":2,"g":1,"r":1,"a":2,"t":2,"u":1,"l":1,"i":1,"s":1}

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?
0 Comments