user2623706
user2623706

Reputation: 527

JavaScript - how to change elements of a string?

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");

Upvotes: 3

Views: 251

Answers (3)

Bastian Rang
Bastian Rang

Reputation: 2187

Doing the same thing with String Prototyping and some shorthand notation.

String.prototype.swapCase = function(){
    var returnString = '';
    for (var i = 0; i < this.length; i++) {
        returnString += (this[i]===this[i].toUpperCase()) 
        ? this[i].toLowerCase()
        : this[i].toUpperCase();
    }
    return returnString;
};

console.log("Hallo".swapCase());

Upvotes: 1

FrostbiteXIII
FrostbiteXIII

Reputation: 891

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;

}

Upvotes: 1

Sirko
Sirko

Reputation: 74046

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;

}

Upvotes: 6

Related Questions