Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

165
Views
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 answers
Answer question

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 Report

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 Report

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!