JavaScript word alphabet counting function

Asked 1 years ago, Updated 1 years ago, 116 views

 // a function that counts how many times a particular letter (ch) is in a given word
    function countCharacter(word, ch) {
      var count = 0;
      var res = word.toUpperCase();
      var count = res.indexOf(ch);
      if(count === -1){
        count = 0;
      } } else if (count >= 0) {
        count = 1;
        count++;
      }
      return count;
    }
 // a function that counts how many times the alphabet 'A' appears in the word word
    function countA(word) {
      var count = 1;
      var str = word.toUpperCase();
      for(count; count < str.length; count++){
        return str.indexOf('A');
      }
      return count;
    }
 console.log(countCharacter('AbaCedEAee', 'E'); //2
    console.log(countCharacter('AbaCedEA', 'X'));            //0
    console.log(countA('AbaCedEA'));                                //0

I want the result to be 3 instead of 0 in the countA function call, what should I do?

javascript html5 function count

2022-09-22 17:56

1 Answers

Both of the functions you wrote are incorrect in logic.

The indexOf function is written for exception handling and is not key. One repeat statement in the function is enough.

function countCharacter(word, ch) {
  var count = 0;
  word = word.toUpperCase();
  ch = ch.toUpperCase();

  for (var i = 0; i < word.length; i++) {
    if (word[i] === ch) {
      count++;
    }
  }
  return count;
}

function countA (word) {
  countCharacter(word, 'a');
}

If you're just going to get the number, I can also think of the following methods.

function countCharacter (word, ch) {
  return word.length - word.toUpperCase().split(ch.toUpperCase()).join('').length;
}


2022-09-22 17:56

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.