JavaScript allows you to easily work with strings and perform numerous different tasks using them. Often you may need to count the number of times one or more characters occur in a string. In this article, we will learn how to count character occurrence in string in JavaScript.
How to Count Character Occurrence in String in JS
Let us say you have the following string in JavaScript.
var text = 'hello good morning';
Let us say you want to count character occurrence of letter ‘o’ in the above string. For this purpose, we will use a combination of regular expression and match() function. Match function returns an array of all matching items in a given substring.
If you know how to construct a regular expression for the character(s) to be counted, you can use literal regular expression in match() function as shown below.
console.log((text.match(/o/g) || []).length); //logs 4
If you do not know the regular expression for your desired character(s) use RegExp() constructor to generate a regular expression.
console.log((text.match(new RegExp("o", "g")) || []).length); //logs 4
Please note, the above method can be used to count substring occurrence also, not just occurrence of characters.
Here is an example to count occurrence of substring ‘el’ in our original string.
console.log((text.match(/el/g) || []).length); //logs 1 OR console.log((text.match(new RegExp("el", "g")) || []).length); //logs 1
Also, if there are no matches found, then, match() returns null. So we use OR operator (||) to include empty array []. This way, when match() returns null, the length property will not give error but return 0.
The above method is easy to understand but can be slower if you have a large body of text. In such cases, you can also use split() function to count character occurrence.
console.log(text.split("o").length - 1) //logs 4
The above code basically splits the given string by the character to be searched, into a new array and returns the length – 1, since there are that many occurrence of the character.
This method can also be used to count occurrence of substring, not just characters. Here’s an example to count occurrence of substring ‘el’ in our original string.
console.log(text.split("el").length - 1) //logs 1
In this article, we have learnt a couple of simple ways to count character occurrence in string using JavaScript.
Also read:
How to Add Auto Increment ID to Existing Table
JS File Upload Size Validation
How to Print Contents of Div in JavaScript
How to Check if Web Page is Loaded in IFrame or Browser
How to Detect Internet Connection is Offline in JS
Related posts:
Sreeram has more than 10 years of experience in web development, Python, Linux, SQL and database programming.