1

I'm trying to count the number of specific characters in a string, but am getting "0" instead of the correct output. I know there are easier ways to get the solution, but I want to know how to do it this way and what I'm doing wrong.

function countCharacter(str, char) {
  var count = 0;
  for(var i = 0; i < str.length; i++){
    if(str.charAt(i) === char){
      count++;
    }
    return count;
  }
}
countCharacter("My cat is driving my crazy", "a");
1
  • 2
    Put the return outside of the loop Commented Apr 17, 2017 at 12:33

4 Answers 4

4
+50

Youre returning in the for loop, so the forloop just iterates once:

function countCharacter(str, char) {
  var count = 0;
  for(var i = 0; i < str.length; i++){
    if(str.charAt(i) === char){
      count++;
    }
  }
 return count;
}
countCharacter("My cat is driving my crazy", "a");

By the way, shorter:

countCharacter=(str,char)=>str.split("").reduce((count,letter)=>letter===char?count+1:count,0);
Sign up to request clarification or add additional context in comments.

Comments

3

Return count should be in a place out of the loop

Comments

2

You can try split and filter. The length of the resulting Array is the number of found characters:

const aFound = "My cat is driving my crazy"
  .split("")                     // split per character
  .filter( chr => chr === "a" ); // filter on character 'a'

const numberOfz = findCharacterInString("I'm driving my cat crazy", "z");

document.querySelector("pre").textContent = `
  There is/are ${aFound.length} a('s) in "My cat is driving my crazy"
  There is/are ${numberOfz} z('s) in "I'm driving my cat crazy"`;
  
// As method (case insensitive)
function findCharacterInString(string2Search, character) {
  return string2Search
    .split("")
    .filter( chr => chr.toLowerCase() === character.toLowerCase() )
    .length;
}
<pre></pre>

Comments

1

You accidentally put your return statement inside your for loop, so it returns after the first time it runs through the loop. Fixed below:

function countCharacter(str, char) {
  var count = 0;
  for(var i = 0; i < str.length; i++){
    if(str.charAt(i) === char){
      count++;
    }
  }
  return count;
}
countCharacter("My cat is driving my crazy", "a");

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.