Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Swap Cases- switch from lowercase to uppercase and viceversa

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(" ")
  } 

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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"))
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading