) 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
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.
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.
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"))