sajad torkamani

TLDR

You want a function that takes two arguments – a string and a character – and returns the number of times the character appears in the string:

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

Here’s how:

function getCharCount(str, char) {
  return (str.match(new RegExp(char, 'gi')) || []).length
}

Explanation

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 the given char is b, 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: Snippets

Leave a comment

Your email address will not be published. Required fields are marked *