How to check how many times a character occurs in a string in JavaScript

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:

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.

Sajad Torkamani

Hello! My name is Sajad. I’m a software developer at Nationwide and an aspiring entrepreneur. Originally from Afghanistan, I moved to London at an early age and have been living here for the past 20 years.

This is my personal website where I blog mostly about programming with occasional thoughts on a bunch of other things. I write mainly for my own benefit as I find that writing helps clarify my otherwise very confused thoughts.

Get in touch: