Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Alternate casing a string in JavaScript
We are required to write a JavaScript function that takes in a string and constructs a new string with all the uppercase characters from the original string converted to lowercase and all the lowercase characters converted to uppercase from the original string.
For example: If the string is ?
const str = 'The Case OF tHis StrinG Will Be FLiPped';
Expected Output
Then the output should be ?
const output = 'tHE cASE of ThIS sTRINg wILL bE flIpPED';
Using Manual Character Code Manipulation
This approach manually checks character codes and applies the ASCII difference between uppercase and lowercase letters (32):
const str = 'The Case OF tHis StrinG Will Be FLiPped';
const isUpperCase = char => char.charCodeAt(0) >= 65 && char.charCodeAt(0) <= 90;
const isLowerCase = char => char.charCodeAt(0) >= 97 && char.charCodeAt(0) <= 122;
const flipCase = str => {
let newStr = '';
const margin = 32;
for(let i = 0; i < str.length; i++){
const curr = str[i];
if(isLowerCase(curr)){
newStr += String.fromCharCode(curr.charCodeAt(0) - margin);
}else if(isUpperCase(curr)){
newStr += String.fromCharCode(curr.charCodeAt(0) + margin);
}else{
newStr += curr;
};
};
return newStr;
};
console.log(flipCase(str));
tHE cASE of ThIS sTRINg wILL bE flIpPED
Using Built-in String Methods (Simpler Approach)
A more readable approach using JavaScript's built-in toUpperCase() and toLowerCase() methods:
const flipCaseSimple = str => {
return str.split('').map(char => {
if (char === char.toUpperCase() && char !== char.toLowerCase()) {
return char.toLowerCase();
} else if (char === char.toLowerCase() && char !== char.toUpperCase()) {
return char.toUpperCase();
} else {
return char; // Non-alphabetic characters remain unchanged
}
}).join('');
};
const testStr = 'Hello World 123!';
console.log(flipCaseSimple(testStr));
hELLO wORLD 123!
Comparison of Methods
| Method | Readability | Performance | Handles Non-English? |
|---|---|---|---|
| Character Code Manipulation | Lower | Faster | No |
| Built-in Methods | Higher | Slightly slower | Yes |
Key Points
- ASCII codes for uppercase letters: 65-90 (A-Z)
- ASCII codes for lowercase letters: 97-122 (a-z)
- The difference between corresponding cases is always 32
- Non-alphabetic characters remain unchanged in both approaches
Conclusion
Both methods effectively flip the case of alphabetic characters. Use the built-in method approach for better readability and Unicode support, or the manual approach for slightly better performance with ASCII-only text.
