0

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')
Markus
  • 15
  • 5

3 Answers3

5

You can use regex to do the same.

const str = 'HeLLo';

console.log(
  (str.match(/[A-Z]/g) || '').length
)
Pranav C Balan
  • 113,687
  • 23
  • 165
  • 188
  • This writing form is new for me and I don't understand it. Is there any way to improve my function with a loop method? – Markus Mar 15 '20 at 19:55
  • @Markus : it's simply extracting all single capital character from the string into an array and checking the length – Pranav C Balan Mar 15 '20 at 19:56
0

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;
}
0

You can use charCodeAt() and if it is between 65 (A) and 90 (Z) it means it is an upper case letter:

const bigLettersCount = (str) => {
  let result = 0;
  for (let i = 0; i < str.length; i += 1) {
    if (str.charCodeAt(i) > 64 && str.charCodeAt(i) <91 ) {
      result += 1;
    }
   }
   return result
  }
  
console.log(bigLettersCount('HeLLo'))
Mechanic
  • 5,015
  • 4
  • 15
  • 38