Convert mixed case string to lower case in JavaScript


Problem

We are required to write a JavaScript function convertToLower() that takes in a string method that converts the string it is being called upon into lowercase string and returns the new string.

For example, if the input to the function is

Input

const str = 'ABcD123';

Output

const output = 'abcd123';

Example

Following is the code −

 Live Demo

const str = 'ABcD123';
String.prototype.convertToLower = function(){
   let res = '';
   for(let i = 0; i < this.length; i++){

      const el = this[i];
      const code = el.charCodeAt(0);
      if(code >= 65 && code <= 90){
         res += String.fromCharCode(code + 32);
      }else{
         res += el;
      };
   };
   return res;
};
console.log(str.convertToLower());

Output

abcd123

Updated on: 24-Apr-2021

248 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements