JavaScript Exercises Basic#11 - Counting only uppercase letters from the string

JavaScript Exercises Basic#11 - Counting only uppercase letters from the string

You will be given a string. Write a program which returns how many UPPERCASE letters there are in the string.

Result Example

Screenshot 2022-04-20 at 17.16.17.png 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).

  1. Declare a variable called 'answer' to keep the count and initiate it with 0.
  2. 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.
  3. 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.

  1. Declare a variable called 'answer' to keep the count and initiate it with 0.
  2. 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.
  3. ASCII value of uppercase alphabets are 65 to 90. Write an if statement to find letters which have ASCII value between 65 and 90.
  4. 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;
           }