Swapcase function in JavaScript


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

Updated on: 11-Dec-2020

397 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements