Languages
[Edit]
EN

JavaScript - count character occurrences

7 points
Created by:
Cassia
1235

In this article, we would like to show you how to count the number of characters that were used in some text using JavaScript.

Quick solution:

// ONLINE-RUNNER:browser;

const countCharacters = (input) => {
	const counts = {};
	for (const entry of input) {
		const count = counts[entry] ?? 0;
		counts[entry] = count + 1;
	}
	return counts;
};


// Usage example:

const input = 'This is some text...';
const counts = countCharacters(input);

for (const key in counts) {
  	console.log(key + ' ' + counts[key]);
}

Output:

T 1
h 1
i 2
s 3
  3
o 1
m 1
e 2
t 2
x 1
. 3

 

Alternative titles

  1. JavaScript - count letter occurrences in text
  2. JavaScript - count character occurrences in string
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.

Cross technology - count character occurrences

Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join