3

This is my first question on Stack, so please excuse me if I'm not asking this correctly.

I'm trying to solve a basic exercise that asks me to create a function named countCharacters that accepts two parameters, a character and a string. It should return the number of times the character is present in the string. This is what I have so far:

function countCharacters(char, string) {

     return string.indexOf(char);

}

Please let me know where I went wrong. I'm still learning basic JavaScript and I appreciate any and all feedback!

Leon Gaban
  • 36,509
  • 115
  • 332
  • 529

2 Answers2

0

The easiest method you can think of is to use a loop, which checks every character, and updates a counter:

console.log(countCharacters('a', 'abbabaa'));

function countCharacters(char, string) {
    var counter = 0;
    for(var i=0; i<string.length; i++){
        if(string[i] === char){ counter++; }
    }
    return counter;
}

You can also use regex to remove any character that is not the one, and return the new length:

console.log(countCharacters('a', 'abbabaa'));

function countCharacters(char, string) {
    var regex = new RegExp('[^' + char + ']', 'g');
    return string.replace(regex,'').length;
}

... or use filter:

console.log(countCharacters('a', 'abbabaa'));

function countCharacters(char, string) {
  return string.split('').filter(c => c===char).length;
}

In your code, you are using indexOf, which returns the position of the first occurence of the character. It does not count them.

blex
  • 24,941
  • 5
  • 39
  • 72
-1

The thing you're doing wrong is that you're finding the position of the char instead of the number of times it has occured in the string. Please note that string.indexOf(char); gives you the index (position) of the occurence of char in your string.

Divyanshu Maithani
  • 13,908
  • 2
  • 36
  • 47
  • @Dave2e the OP asked "Please let me know where I went wrong" and I've answered where he went wrong. The question is already marked duplicate (after I had already answered). I shall update my answer nevertheless. – Divyanshu Maithani Oct 17 '16 at 04:39