Search code examples
javascriptfor-loopequalitymutationtoupper

How to count all uppercase characters in a string?


I stuck on a function that supposed to count upper letters in a string. But instead the counter results in 0 and I've no idea where I made a mistake.

const bigLettersCount = (str) => {
  let result = 0;
  for (let i = 0; i < str.length; i += 1) {
    if (str[i].toUpperCase() === str[i]) {
    result += i;
    }
    return result;
   }
  }
  bigLettersCount('HeLLo')

Solution

  • I have updated your code like below. It will work.

    const bigLettersCount = (str) => {
    let result = 0;
    for (let i = 0; i < str.length; i += 1) {
      if (str[i].toUpperCase() === str[i]) {
        result++;
      }
    }
    return result;
    }