Create a custom toLowerCase() function in JavaScript

JavascriptWeb DevelopmentObject Oriented Programming

We are required to write a JavaScript String function that overwrite the default toLowerCase() and should have the same functionality as the default function.

Let's write the code for this function −

Example

const str = 'Some UpPerCAsE LeTTeRs!!!';
const toLowerCase = function(){
   let str = '';
   for(let i = 0; i < this.length; i++){
      const ascii = this[i].charCodeAt();
      if(ascii >= 65 && ascii <= 90){
         str += String.fromCharCode(ascii + 32);
      }else{
         str += this[i];
      };
   };
   return str;
};
String.prototype.toLowerCase = toLowerCase;
console.log(str.toLowerCase());

Output

The output in the console will be −

some uppercase letters!!!
raja
Published on 31-Aug-2020 12:25:21
Advertisements