-3

e.g count("Good", "o") result: 2

I'm not looking for it to be fast, I just need something that is simple and works.

1 Answers1

0

You can use match to find occurrences of a character in a string and create an array of the matches. Using .length will tell you how many. The 'g' flag in the RegExp is used to match all occurrences and not just the first.

function count(str, find) {
    return (str.match(RegExp(find,'g')) || []).length
}

count("Good", "o");

The RegExp solution above does not work if the character you are looking for is a special RegExp character such as ., |, +, etc.

The following is an alternative solution which does not use RegExp (which is also possibly faster):

function count(str, find) {
    return (str.split(find)).length - 1;
}

count("Good", "o");

This function splits the string into an array at each occurrence of your character. (Ex. Good becomes ['G','','d']). The size of this array is always one more than the number of occurrences since it includes both ends. Therefore, you can get the length of this array and subtract 1.

DenverCoder1
  • 2,253
  • 1
  • 10
  • 23