JS newbie here. I want to write a basic program that changes each element in a string based on a condition. If the letter is uppercase we swap it to lowercase, if the letter is already lowercase we swap it to uppercase. Why is this not working? Thanks!
function SwapCase(str){
for (var i = 0; i < str.length; i++) {
if (str.charAt(i)===str.charAt(i).toUpperCase()) {
str.charAt(i).toLowerCase();
} else{}
str.charAt(i).toUpperCase();
}
return str;
}
SwapCase("gEORGE");
Currently you do not write back your changes. You could, for example, do something like this:
function SwapCase(str){
var result = '';
for (var i = 0; i < str.length; i++) {
if (str.charAt(i)===str.charAt(i).toUpperCase()) {
result += str.charAt(i).toLowerCase();
} else{
result += str.charAt(i).toUpperCase();
}
}
return result;
}
function SwapCase(str){
var sReturn = "";
for (var i = 0; i < str.length; i++) {
if (str.charAt(i)===str.charAt(i).toUpperCase()) {
sReturn += str.charAt(i).toLowerCase();
} else{
sReturn += str.charAt(i).toUpperCase();
}
}
return sReturn;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With