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,
The array should not run to length, so it should be
<
instead of<=
There is no need for 3 loops
result.join should join with an empty string instead of blank space
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"))