-1

) 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

Markitos
  • 13
  • 1
  • I guess you should ignore spaces as `" "` capitalized is still `" "`, so that is also being counted (you'll have this issue with other characters, such as punctuation) – Nick Parsons Jan 09 '22 at 04:48

4 Answers4

1

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.

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.

Tim Biegeleisen
  • 502,043
  • 27
  • 286
  • 360
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"))
Jay Patel
  • 1,098
  • 7
  • 22
0

Problem is your spacing.

" How many Caps"

has 3 spaces and 2 capital letters.. that should help you debug

JJZ
  • 56
  • 4