Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Specific character count in string

So guys, I want to make a specific character counter, f.g. in word Specific we have 2 "i". Where am I wrong?

function countChar(word, char) {
  var count = 0
  for (let i = 0; i <= word.lenght; i++) {
    if (word[i] === `${char}`) {
      count += 1
    }
  }
  return count;
}
console.log(countChar("BBC","B"));
//0
//undefined

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Hi and welcome to stackoverflow!

You have two problems in your code:

  • typo word.length instead of word.lenght
  • word[i] instead of string[i] in the comparison

So, your code works when you use

<!DOCTYPE html>
<html>
<head>
<script type='text/javascript'>
function countChar(word, char) {
  var count = 0
  for (let i = 0; i <= word.length; i++) {
    if (word[i] === `${char}`) {
      count += 1
    }
  }
  return count;
}
alert (countChar("BBC","B"));
</script>
</head>
<body>
</body>
</html>

Please use a debugger, like the ones that are contained in every modern browser in the future ;-).

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading