Alternate casing a string in JavaScript

JavascriptWeb DevelopmentFront End TechnologyObject Oriented Programming

We are required to write a JavaScript function that takes in a string and constructs a new string with all the uppercase characters from the original string converted to lowercase and all the lowercase characters converted to uppercase from the original string.

For example: If the string is −

const str = 'The Case OF tHis StrinG Will Be FLiPped';


Then the output should be −

const output = 'tHE cASE of ThIS sTRINg wILL bE flIpPED';


The code for this will be −

const str = 'The Case OF tHis StrinG Will Be FLiPped';
const isUpperCase = char => char.charCodeAt(0) >= 65 && char.charCodeAt(0)<= 90;
const isLowerCase = char => char.charCodeAt(0) >= 97 && char.charCodeAt(0) <= 122;
const flipCase = str => {
   let newStr = '';
   const margin = 32;
   for(let i = 0; i < str.length; i++){
      const curr = str[i];
         newStr += String.fromCharCode(curr.charCodeAt(0) - margin);
      }else if(isUpperCase(curr)){
         newStr += String.fromCharCode(curr.charCodeAt(0) + margin);
         newStr += curr;
   return newStr;


The output in the console −

tHE cASE of ThIS sTRINg wILL bE flipped
Updated on 15-Oct-2020 09:31:56