How to count the occurrences of a character in a string in JavaScript

In this Article we will go through how to count the occurrences of a character in a string only using single line of code in JavaScript. This is a one-line JavaScript code snippet that uses one of the most popular ES6 features => Arrow Function.

Let's define this short function:

const countOccurrences = (str, char) => [...str].reduce((a, v) => (v === char ? a + 1 : a), 0);

#Or

const countOccurrences = (str, char) => str.split('').reduce((a, v) => (v === char ? a + 1 : a), 0);

#Or

const countOccurrences = (str, char) => [...str].filter(item => item === char).length;

#Or

const countOccurrences = (str, char) => str.split('').filter(item => item === char).length;

#Example

countOccurrences('a.b.c.d.e', '.');     // 4
\n