You will be given a string. Write a program which returns how many UPPERCASE letters there are in the string.
Result Example
Solution1 -Using String.prototype.toUpperCase() method
String.prototype.toUpperCase() The toUpperCase() method returns the calling string value converted to uppercase (the value will be converted to a string if it isn't one).
- Declare a variable called 'answer' to keep the count and initiate it with 0.
- Use for...of loop to iterate through the string and compare all of the letters with the uppercased version of itself. Use the strict equality operator(===) here. If they match, increment the count.
- Return 'answer'.
function solution(str){
let answer = 0;
for (let x of str){
if (x === x.toUpperCase()) answer++;
}
return answer;
}
Solution2 -Using String.prototype.charCodeAt() method
String.prototype.charCodeAt() The charCodeAt() method returns an integer between 0 and 65535 representing the UTF-16 code unit at the given index.
- Declare a variable called 'answer' to keep the count and initiate it with 0.
- Use for...of loop to iterate through the string. We need a new variable here, let's call it 'num'. Store the UTF-16 code unit value(ASCII value) of each letters using charCodeAt() method.
- ASCII value of uppercase alphabets are 65 to 90. Write an if statement to find letters which have ASCII value between 65 and 90.
- Return 'answer'.
function solution(str){
let answer = 0;
for (let x of str){
let num = x.charCodeAt();
if (num >= 65 && num <= 90) answer++;
}
return answer;
}