Adding a function for swapping cases to the prototype object of strings - JavaScript

JavascriptWeb DevelopmentFront End TechnologyObject Oriented Programming

In JavaScript, we can write our own custom functions and assign them to the existing standard data types (it is quite similar to writing library methods but in this case the data types are primitive and not user defined. We are required to write a JavaScript String function by the name, let’s say swapCase().

This function will return a new string with all uppercase characters swapped for lower case characters, and vice versa. Any non-alphabetic characters should be kept as they are.

Example

Following is the code −

const str = 'ThIS iS A CraZY StRInG';
String.prototype.swapCase = function(){
   let res = '';
   for(let i = 0; i < this.length; i++){
      if(this[i].toLowerCase() === this[i].toUpperCase()){
         res += this[i];
         continue;
      };
      if(this[i].toLowerCase() === this[i]){
         res += this[i].toUpperCase();
         continue;
      };
      res += this[i].toLowerCase();
   };
   return res;
};
console.log(str.swapCase());

Output

Following is the output in the console −

tHis Is a cRAzy sTriNg
raja
Updated on 18-Sep-2020 09:38:08

Advertisements