Open In App

Convert Characters of a String to Opposite Case in JavaScript

Last Updated : 01 Dec, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

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

  • In this approach, we are iterating over each character of inputStr using for loop.
  • Using the if condition, we are checking if the character is lowerCase then we convert it to upperCase and store the results in the output variable.
  • In the else block, the vice versa has been done.

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

Javascript




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

  • In this approach, iterating over the inputStr then determining its ASCII value and converting it to the opposite case.
  • If a character is uppercase then it is converted into lowercase and vice versa.

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

Javascript




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

  • In this approach, we are using regular expressions to match the alphabetic characters in inputStr.
  • Then by using the replace() method we covert the case of each matched character and store it in the output variable.

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

Javascript




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


Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads