Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

81
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda