Categories
JavaScript Answers

How to Count the Number of Occurrences for Each Character in a JavaScript String?

Spread the love

To count the number of occurrences for each char in a JavaScript string, we can create an object that keeps track of how many characters are in each string.

Then we can loop through each character of the string with a for-of loop.

For instance, we can write:

const countChar = (str) => {
  const counts = {};
  for (const s of str) {
    if (counts[s]) {
      counts[s]++
    } else {
      counts[s] = 1
    }
  }
  return counts;
}

const str = "I want to count the number of occurences of each char in this string";
console.log(countChar(str))

to count the number of occurrences in each character in str with the countChar function.

Then function loops through each character of string str with the for-of loop.

Next, we create the counts object to keep track of the count of each character.

Then if count[s] exists, we increment it by 1.

Otherwise, we set count[s] to 1.

And then when the loop is done, we return the counts object.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

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