Home > OS >  Swap Cases- switch from lowercase to uppercase and viceversa
Swap Cases- switch from lowercase to uppercase and viceversa

Time:03-13

Given a string I am supposed to make all the lowercase letters to uppercase and vice versa. I tried this and but can not figure out why it is wrong. The output gives me: Can not read property .toLowerCase() of undefined.

    function SwapCase(str) { 
let cap=str.toUpperCase
let low=str.toLowerCase
let arr=str.split("")  
let result=[]

for(var i=0; i<=arr.length;i  ){  
  for(var j=0; j<=cap.length;j  ){ 
for( var k=0; k<=low.length;k  ){ 
  if(arr[i]===cap[j]){ 
     result.push(arr[i].toLowerCase())
  } 
  if(arr[i]===low[k]){ 
     result.push(arr[i].toUpperCase())
  }
}
  

} } 
  return result.join(" ")
  } 

CodePudding user response:

There are multiple issues with this code,

  1. The array should not run to length, so it should be < instead of <=

  2. There is no need for 3 loops

  3. result.join should join with an empty string instead of blank space

  4. Intendations are all over the place.

see corrected code below:

function SwapCase(str) { 
  let cap=str.toUpperCase()
  let low=str.toLowerCase()
  let arr=str.split("")  
  let result=[]

  for(var i=0; i<arr.length;i  ){  
    if(arr[i]===cap[i]){ 
      result.push(arr[i].toLowerCase())
    } 
    if(arr[i]===low[i]){ 
      result.push(arr[i].toUpperCase())
    }
  } 
  return result.join("")
}

console.log(SwapCase("heLLo"))

  • Related