Replacing upperCase and LowerCase in a string - JavaScript



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

Let’s write the code for this function βˆ’

Example

Following is the code βˆ’

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];
      if(isLowerCase(curr)){
         newStr += String.fromCharCode(curr.charCodeAt(0) - margin);
      }else if(isUpperCase(curr)){
         newStr += String.fromCharCode(curr.charCodeAt(0) + margin);
      }else{
         newStr += curr;
      };
   };
   return newStr;
};
console.log(flipCase(str));

Output

The output in the console: βˆ’

tHE cASE of ThIS sTRINg wILL bE flIpPED
Updated on: 2020-09-15T10:36:33+05:30

606 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements