Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

98
Visualizações
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
about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

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 ;-).

about 4 years ago · Juan Pablo Isaza Relatório

0

There is a typing mistake in for loop. Write length instead of lenght.

Here is working code

function countChar(word, char) {
    var count = 0
    for (let i = 0; i <= word.length; i++) {
        if (word[i] === `${char}`) {
            count += 1
        }
    }
    return count;
}
console.log(countChar("BBC","B"));
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda