sajad torkamani

When solving katas on Codewars, I often find myself needing to do some variation of find out how many times a character occurs in a given string and then doing some further steps with the result.

Here's my preferred solution to this common task:

const getCharCount = (str, char) => {
  return (str.match(new RegExp(char, 'gi')) || []).length

console.log(getCharCount('fizzbuzz', 'z')) // 4
console.log(getCharCount('JAVASCRIPT', 'a')) // 2

We make use of the RegExp constructor to create a dynamic regular expression using the provided char. We also pass the global match flag g to find all occurrences of char as well as the ignore case flag i to make the search case-insensitive.

This means that if char is b for example, the regex would /b/gi . If char is c , it would be /c/gi and so on.

Once we have the regex built, we pass it to String.match to find all occurrences of that regex within the given string. String.match will return an array of all the matches or null if no matches were found.

To make our code easier to read, we will just cast any null results to an empty array [] so that we can then simply check for the array's length to find the number of occurrences.

Tagged: JavaScript