Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript - how to change elements of a string?

Tags:

javascript

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");
like image 882
user2623706 Avatar asked May 29 '26 04:05

user2623706


2 Answers

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;

}
like image 125
Sirko Avatar answered May 31 '26 18:05

Sirko


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;

}
like image 44
FrostbiteXIII Avatar answered May 31 '26 16:05

FrostbiteXIII



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!