Change the case without using String.prototype.toUpperCase() in JavaScript

JavascriptWeb DevelopmentFront End Technology

Problem

We are required to write a JavaScript function that lives on the prototype object of the string class.

This function should simply change case of all the alphabets present in the string to uppercase and return the new string.

Example

Following is the code −

 Live Demo

const str = 'This is a lowercase String';
String.prototype.customToUpperCase = function(){
   const legend = 'abcdefghijklmnopqrstuvwxyz';
   const UPPER = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
   let res = '';
   for(let i = 0; i < this.length; i++){
      const el = this[i];
      const index = legend.indexOf(el);
      if(index !== -1){
         res += UPPER[index];
      }else{
         res += el;
      };
   };
   return res;
};
console.log(str.customToUpperCase());

Output

Following is the console output −

THIS IS A LOWERCASE STRING
raja
Published on 17-Apr-2021 11:58:55
Advertisements