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

83
Visualizações
Count the capitals in the word javascript

) I am trying to solve one problem with this statement :

Write a function called howManyCaps which counts the capitals in the word,it then returns a sentence saying how which letters are capital and how many capitals there are in total.

This is my function

function howManyCaps(str) {
  var count = 0;
  for (i = 0; i < str.length; i++) {
    if (str[i] == str[i].toUpperCase()) {
      console.log(true);
      count++;
    } else {
      false;
    }
  }
  return count;
}

but in console if try with something like str=" How many Caps" y see a value of 5 instead of 2. Any suggestions? Thanks

about 4 years ago · Juan Pablo Isaza
3 Respostas
Responde à pergunta

0

The simplest way is [O(N)]:

function howManyCaps(str) {
    let upper = 0;
    for (let i = 0; i < str.length; i++) {
        if (str[i] >= 'A' && str[i] <= 'Z') upper++;
    }
    return upper;
};

howManyCaps(' How many Caps');

Some people are saying don't use spaced or account for spaces, but that also is not a good strategy because it will also break for special characters.

about 4 years ago · Juan Pablo Isaza Relatório

0

If regular expressions are available to you, I would suggest the following:

function howManyCaps(str) {
    return str.length - str.replace(/[A-Z]+/g, "").length;
}

var str = " How many Caps";
console.log("Input has " + howManyCaps(str) + " capital letters.");

The idea is to compare the length of the original input against the length of the input with all capital letters removed.

about 4 years ago · Juan Pablo Isaza Relatório

0

The better way is to use regex Below is the code

function howManyCaps(str) {
    return str.replace(/[^A-Z]/g, '').length;
}
console.log(howManyCaps(" How many Caps"))

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