This post will discuss how to count the total number of occurrences of a character in a string with JavaScript.

1. Using Regex

Regular expressions are often used in JavaScript for matching a text with a pattern. The following code example demonstrates its usage to get the count of the characters in the string. It uses the match() method of the string instance.

Download  Run Code

 
The match() method returns null if there were no matches. To avoid calling the length property on the null value, we have used the logical OR operator [].

2. Using String.prototype.split() function

Here, the idea is to split the string using the given character as a delimiter and determine the count using the resulting array’s length. This can be easily done using the split() method:

Download  Run Code

3. Using Array.prototype.filter() function

Another alternative is to filter the array to allow only those values matching the given character. This would translate to a simple code below:

Download  Run Code

4. Using Underscore/Lodash Library

If you prefer Underscore or Lodash library, you can use the _.countBy method. It basically groups characters of the array and returns counts for each character. You can use it as:

Download Code

That’s all about counting the number of occurrences of a character in a string in JavaScript.