JavaScript - Characterrs to Opposite Case in a String
Last Updated : 17 Nov, 2024
Here are the various approaches to convert each character of a string to its opposite case (uppercase to lowercase and vice versa).
Using for Loop and if-else Condition - Most Common
In this approach, we iterate through each character of the string. Using an if-else statement, it checks if each character is uppercase or lowercase and converts it accordingly.
JavaScript const s1 = "Hello World"; let s2 = ""; for (let i = 0; i < s1.length; i++) { const char = s1[i]; s2 += char === char.toUpperCase() ? char.toLowerCase() : char.toUpperCase(); } console.log(s2);
Using ASCII Values
Using ASCII values, you can determine whether a character is uppercase or lowercase, then convert it by adjusting its ASCII code. This method is useful for complex strings.
JavaScript const s1 = "Hello World"; let s2 = ""; for (let i = 0; i < s1.length; i++) { const charCode = s1.charCodeAt(i); if (charCode >= 65 && charCode <= 90) { s2 += String.fromCharCode(charCode + 32); } else if (charCode >= 97 && charCode <= 122) { s2 += String.fromCharCode(charCode - 32); } else { s2 += s1[i]; } } console.log(s2);
Using replace() Method with Regular Expression
The replace() method, along with a regular expression, can convert uppercase letters to lowercase and vice versa in a single line.
JavaScript const s1 = "Hello World"; // Use replace with regex to swap case const s2 = s1.replace(/[a-zA-Z]/g, char => char === char.toUpperCase() ? char.toLowerCase() : char.toUpperCase() ); console.log(s2);
Using split() and map() Method
The split() method splits the string into an array of characters, uses map() to change the case of each character, and then joins the array back into a string.
JavaScript const s1 = "Hello World"; const s2 = s1 .split("") .map(char => (char === char.toUpperCase() ? char.toLowerCase() : char.toUpperCase())) .join(""); console.log(s2);
Using the reduce Method
The reduce() method goes through each character in the string, turning it into an array. For each character, it adds the opposite case (uppercase becomes lowercase and vice versa) to the result. Finally, it joins everything back into a single string.
JavaScript function swapCase(str) { return str.split('').reduce((acc, char) => { return acc + (char === char.toUpperCase() ? char.toLowerCase() : char.toUpperCase()); }, ''); } console.log(swapCase("Hello World!"));
Using Array.from() Method
Array.from() converts the string into an array, allowing you to change each character’s case and join them back together.
JavaScript const s1 = "Hello World"; const s2 = Array.from(s1, char => char === char.toUpperCase() ? char.toLowerCase() : char.toUpperCase() ).join(""); console.log(s2);
Using for…of Loop and Ternary Operator
We can combine for...of loop with a ternary operator to check and convert each character’s case.
JavaScript const s1 = "Hello World"; let s2 = ""; for (const char of s1) { s2 += char === char.toUpperCase() ? char.toLowerCase() : char.toUpperCase(); } console.log(s2);
Similar Reads
Convert a String to a List of Characters in Java In Java, to convert a string into a list of characters, we can use several methods depending on the requirements. In this article, we will learn how to convert a string to a list of characters in Java.Example:In this example, we will use the toCharArray() method to convert a String into a character
3 min read
Convert List of Characters to String in Java Given a list of characters. In this article, we will write a Java program to convert the given list to a string. Example of List-to-String ConversionInput : list = {'g', 'e', 'e', 'k', 's'} Output : "geeks" Input : list = {'a', 'b', 'c'} Output : "abc" Strings - Strings in Java are objects that are
4 min read
Javascript Program To Reverse Words In A Given String Example: Let the input string be "i like this program very much". The function should change the string to "much very program this like i"Examples:Â Input: s = "geeks quiz practice code"Â Output: s = "code practice quiz geeks"Input: s = "getting good at coding needs a lot of practice"Â Output: s = "pra
4 min read
Javascript Program to Modify a string by performing given shift operations Given a string S containing lowercase English alphabets, and a matrix shift[][] consisting of pairs of the form{direction, amount}, where the direction can be 0 (for left shift) or 1 (for right shift) and the amount is the number of indices by which the string S is required to be shifted. The task i
3 min read
JavaScript String Methods JavaScript strings are the sequence of characters. They are treated as Primitive data types. In JavaScript, strings are automatically converted to string objects when using string methods on them. This process is called auto-boxing. The following are methods that we can call on strings.slice() extra
11 min read