JavaScript Exercises Basic#12 - String to Uppercase

JavaScript Exercises Basic#12 - String to Uppercase

You will be given a string with mixed upper and lower case letters. Write a program which returns UPPERCASED string.

Result Example Screenshot 2022-04-21 at 14.43.38.png

Solution

  1. Declare a variable named 'answer' and store an empty string.
  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, it means the letter is already uppercased. Just add it to the 'answer' string. If they don't, make it an uppercased letter with toUpperCase() method and add it to the 'answer' string.
  3. Return 'answer'.
function solution(str){
               let answer = '';
               for (let x of str){
                   if (x === x.toUpperCase()) {
                        answer += x;
                   } else {
                       answer += x.toUpperCase();
                   }
               }

               return answer;

Other Solutions

function solution(str){
               return str.toUpperCase();
           }
function solution(str){
                let answer = '';
                for (let x of str){
                    if (x === x.toLowerCase()){
                        answer += x.toUpperCase();
                    } else {
                        answer += x;
                    }
                }

                return answer;
            }
function solution(str){
               let answer = '';
               for (let x of str){
                   let num = x.charCodeAt();
                   if (num >= 97 && num <= 122){ //if the ASCII code of x is between 97 and 122, it means the letter x is lowercase
                       answer += String.fromCharCode(num - 32); //change it to the uppercased letter before add it to the answer string
                   } else {
                       answer += x;
                   }
               }

               return answer;
           }