Count number of occurrences of a character in a string in JavaScript
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.
|
1 2 3 4 5 6 7 8 |
var str = "A,B,C,D,E"; var count = (str.match(/\,/g) || []).length; console.log(count); /* Output: 4 */ |
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:
|
1 2 3 4 5 6 7 8 9 |
var str = "A,B,C,D,E"; var ch = ','; var count = str.split(ch).length - 1; console.log(count); /* Output: 4 */ |
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:
|
1 2 3 4 5 6 7 8 9 |
var str = "A,B,C,D,E"; var ch = ','; var count = [...str].filter(x => x === ch).length; console.log(count); /* Output: 4 */ |
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:
|
1 2 3 4 5 6 7 8 9 10 11 |
var _ = require('lodash'); // or underscore.js var str = "A,B,C,D,E"; var ch = ','; var count = _.countBy(str)[ch]; console.log(count); /* Output: 4 */ |
That’s all about counting the number of occurrences of a character in a string in JavaScript.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)