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

173
Vistas
count forEach loop in JavaScript

I am trying to find the total number of a specific character is in string.

for example

myString = " this is my string ";

I want to count how many "s" is in myString. I tried the following:

function myFunction(a, b) {
  const letters = b.split("");
  console.log(letters);
 
  letters.forEach(letter => {
    let letterCount = 0;
    if(letter === a) {
      console.log("yes")
      letterCount++;       
    }
    console.log(letterCount);      
  })
}

myFunction('s', 'this is my string') // Expected result: 3
about 4 years ago · Santiago Trujillo
3 Respuestas
Responde la pregunta

0

Filter is a proper way to achieve that.

'this is my string'.split('').filter(s => s === 's').length
about 4 years ago · Santiago Trujillo Denunciar

0

You can use split to do this:

myString = " this is my string ";
console.log(myString.split('s').length - 1);

about 4 years ago · Santiago Trujillo Denunciar

0

You can use reduce to get info of all chars:

function countRepeatedChars(str) {
  return str.split('').reduce((acc, val) => {
    acc[val] = acc[val] ? ++acc[val] : 1
    
    return acc
  }, {})
}

console.log(countRepeatedChars('dfgdfghdfghdfhdfhwefw'))

about 4 years ago · Santiago Trujillo 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