Open In App

Convert Characters of a String to Opposite Case in JavaScript

In this article, we will be converting characters of a string to opposite cases in JavaScript. We have given a string and we need to convert the string to characters in opposite case i.e. if the character is in lowercase then convert it into uppercase and vice versa.

Examples:

Input : geeksForgEeks
Output : GEEKSfORGeEKS
Input : hello every one
Output : HELLO EVERY ONE

Approach 1: Using For Loop and If-Else Condition

Example: In this example, we are converting characters of a string to opposite case in JavaScript using a For Loop and If-Else Condition.




let inputStr = "geeksForgEeks";
let output = "";
 
for (let c of inputStr) {
    if (c === c.toLowerCase()) {
        output += c.toUpperCase();
    } else {
        output += c.toLowerCase();
    }
}
 
console.log(output);

Output

GEEKSfORGeEKS

Approach 2: Using ASCII Values

Example: In this example, we are converting characters of a string to the opposite case in JavaScript using ASCII Values.




let inputStr = "hello every one";
let output = "";
 
for (let c of inputStr) {
    let asciVal = c.charCodeAt(0);
    let opCase = '';
     
    if (asciVal >= 65 && asciVal <= 90) {
        opCase = String.fromCharCode(asciVal + 32);
    } else if (asciVal >= 97 && asciVal <= 122) {
        opCase = String.fromCharCode(asciVal - 32);
    } else {
        opCase = c;
    }
    output += opCase;
}
 
console.log(output);

Output
HELLO EVERY ONE

Approach 3: Using Regular Expression and replace() Method

Example: In this example, we are converting characters of a string to the opposite case in JavaScript using Regular Expression and replace() method.




let inputStr = "hello every one";
let output =
    inputStr.replace(/[a-zA-Z]/g, function(c) {
    return c === c.toLowerCase() ?
        c.toUpperCase() : c.toLowerCase();
});
 
console.log(output);

Output
HELLO EVERY ONE

Article Tags :