Swapcase function in JavaScript

JavascriptWeb DevelopmentFront End TechnologyObject Oriented Programming

We are required to write a JavaScript function that takes in a string as the only argument.

The string might contain both uppercase and lowercase alphabets.

The function should construct a new string based on the input string in which all the uppercase letters are converted to lowercase and all the lowercase letters are converted to uppercase.

Example

Following is the code −

const str = 'ThIs Is A STriNG';
const findLetter = (char = '') => {
   if(char.toLowerCase() === char.toUpperCase){
      return char;
   }else if(char.toLowerCase() === char){
      return char.toUpperCase();
   }else{
      return char.toLowerCase();
   };
}
const swapCase = (str = '') => {
   let res = '';
   for(let i = 0; i < str.length; i++){
      const el = str[i];
      res += findLetter(el);
   };
   return res;
};
console.log(swapCase(str));

Output

Following is the output on console −

tHiS iS a stRIng
raja
Updated on 11-Dec-2020 09:22:48

Advertisements