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 task:
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
b for example, the regex would
/b/gi . If
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.