Pawan Kalyan
Pawan Kalyan

Reputation: 581

How to change every character to opposite case in Javascript?

My HTML page is

<!DOCTYPE html>
<html>
<head>
<script>
function changeCase(){
var str=document.getElementById("changeCase").innerHTML;

for(var i=0;i<str.length;i++){
if(str.charAt(i)==''){
console.log("-------------------------");
}
else if(str.charAt(i)===str.charAt(i).toLowerCase()){
str.charAt(i).toUpperCase();

}
else if(str.charAt(i)===str.charAt(i).toUpperCase()){
str.charAt(i).toLowerCase()

}

}
console.log(str,"after");
}
</script>
</head>
<body>
<div style="width:400px;margin:30px auto 0px;">
<p id="changeCase">

Part Of Me Suspects That I'm a Loser, And The Other Part of Me Thinks I'm God Almighty.

</p>
<p><button type="button" onclick="changeCase()">Click Here</button></p>
</div>
</body>
</html>

I want to change the case of the characters in paragraph to their opposite i.e uppercase to lowercase and vice versa... How this could be achieved?

Upvotes: 0

Views: 6070

Answers (9)

Surender Lohia
Surender Lohia

Reputation: 379

    function flipChar(char) {
      const lowercasePat = /[a-z]/;
      
      if(lowercasePat.test(char)) {
        return char.toUpperCase();
      } else {
        return char.toLowerCase();
      }
    }
    
    function flipCharacters(str) {
      const strLen = str.length;
      let flippedStr = '';
      let char;
      
      for(let i = 0; i < strLen; i++) {
        char = str.charAt(i);
        flippedStr += flipChar(char);
      }
    
      return flippedStr;
    }
    
    console.log(flipCharacters('SuReN')); // sUrEn

Upvotes: 0

R. Rd
R. Rd

Reputation: 41

let str = "The Quick Brown Fox";

const newStr = str
  .split("")
  .map(c => (c === c.toUpperCase() ? c.toLowerCase() : c.toUpperCase()))
  .join("");

console.log(newStr);

Upvotes: 4

EdgeDev
EdgeDev

Reputation: 2486

function changeCase(str) {
    var changed = '';

    for (var i = 0; i < str.length; i++) {
        var char = str.charAt(i);
        var charCodeInt = char.charCodeAt(0);
        if (charCodeInt >= 97 && charCodeInt <= 122) {
            changed += char.toUpperCase();
        } else if (charCodeInt >= 65 && charCodeInt <= 90) {
            changed += char.toLowerCase()
        }else changed += char;
    }
    return changed
}

Upvotes: 0

Sam Bennett
Sam Bennett

Reputation: 21

Use the new ES6 spread operator: more info at MDN

// es6 arrow functions
// does this character === the lowercase version of itself? If so, it is lowercase
// this function returns either true or false
const isLowerCase = char => char.toLowerCase() === char;

// another arrow function
// implements a ternary operator (x ? y : z). If x is true return y, else return z
// if the char is lowercase, make it uppercase, else make it lowercase
const swapCase = char => isLowerCase(char) ? char.toUpperCase() : char.toLowerCase();

// ES6 let keyword
// arrow function
// ES6 spead operator [...string] returns an array with each letter in string
// as an element, for every element (char), we run the swapCase func
// to get the opposite case, then join it all back into a string
let alternateCase = string => {
  return [...string].map(swapCase).join('');
};

Upvotes: 2

georg
georg

Reputation: 215039

Here's an elegant (although a bit advanced) solution:

"AbCdEf".replace(/([a-z]+)|([A-Z]+)/g, function(_, low, up) { 
       return low ? low.toUpperCase() : up.toLowerCase() 
})

Upvotes: 3

Shyam
Shyam

Reputation: 792

One more option for change case of strings :

<!DOCTYPE html>
<html>
<head>
<script>
function changeCase(){
    var element = document.getElementById("changeCase"),
        str=element.innerHTML,
        str_new = '';

    for(i=0; i<str.length;i++){
        if(str[i] >= 'a' && str[i] <= 'z') {
            str[i].toUpperCase();
            str_new += str[i].toUpperCase();
        }

        else if(str[i] >= 'A' && str[i] <= 'Z') {
            str[i].toLowerCase();
            str_new += str[i].toLowerCase();
        }

        else str_new += str[i].toLowerCase();
    }

    console.log(str_new, "after");
    element.innerHTML = str_new;

}
</script>
</head>
<body>
<div style="width:400px;margin:30px auto 0px;">
<p id="changeCase">Part Of Me Suspects That I'm a Loser, 123456789 And The Other Part of Me Thinks I'm God Almighty.</p>
<p><button type="button" onclick="changeCase()">Click Here</button></p>
</div>
</body>
</html>

Upvotes: 0

Artyom Neustroev
Artyom Neustroev

Reputation: 8715

Solution with regexp is more readable in my opinion:

function toOppositeCase(char) {
   return (/[a-z]/).test(char) ? char.toUpperCase() : char.toLowerCase();
}
var str = "soMeStrinG",
    str1 = "";
for (var i = 0; i < str.length; i++) {
   str1 += toOppositeCase(str[i]);
}
console.log(str1);

Upvotes: 1

skos
skos

Reputation: 4222

You can store the new string in a variable like this -

function changeCase(){
var str=document.getElementById("changeCase").innerHTML;
var newStr = "";
for(var i=0;i<str.length;i++){
if(str.charAt(i)==''){
    console.log("-------------------------");
}
else if(str.charAt(i)===str.charAt(i).toLowerCase()){
    newStr += str.charAt(i).toUpperCase();

}
else if(str.charAt(i)===str.charAt(i).toUpperCase()){
    newStr += str.charAt(i).toLowerCase()

}

}
  console.log(str,"after");
  document.getElementById("changeCase").innerHTML = newStr;
}

Upvotes: 0

adeneo
adeneo

Reputation: 318342

Strings are immutable, they don't change when using methods like toLowerCase(), they return a new string that is changed, and you have to assign that new string to something :

function changeCase() {
    var str = document.getElementById("changeCase").innerHTML,
        str2 = '';

    for (var i = 0; i < str.length; i++) {
        if (str.charAt(i) === str.charAt(i).toLowerCase()) {
            str2 += str.charAt(i).toUpperCase();
        } else if (str.charAt(i) === str.charAt(i).toUpperCase()) {
            str2 += str.charAt(i).toLowerCase()
        } else {
            str2 += str.charAt(i);
        }
    }
    console.log(str2, "after");
}

FIDDLE

Upvotes: 4

Related Questions