John Degvee John Degvee - 4 months ago 9
Javascript Question

Convert LoverCase to UpperCase and converse (JavaScript)

Have a string for example = 'fGvB233k;'
need result = 'FgVb233K;'

<script>
var str ='fGvb233k;';
var res;
var i;
for (i=0; i < str.length; i++) {
if (str[i] === str[i].toUpperCase())
{
str[i] = str[i].toLowerCase() ;
console.log(str[i]);
}
else {
str[i] = str[i].toUpperCase() ;

}
};
console.log(str);
</script>


my script doesnt work....
result of script:
G
B
2
3
3
;

Answer

Example: JSBin You cannot mutate a string you need to create a new one:

var swapCase = function(letters){
    var str = "";
    for(var i = 0; i<letters.length; i++){
        if(letters[i] === letters[i].toLowerCase()){
            str += letters[i].toUpperCase();
        }else {
            str += letters[i].toLowerCase();
        }
    }
    console.log(str);
    return str;
};