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
Selected Reading
Replacing upperCase and LowerCase in a string - JavaScript
We are required to write a JavaScript function that takes in a string and constructs a new string with all the uppercase characters converted to lowercase and all the lowercase characters converted to uppercase.
Let's write the code for this function ?
Example
Following is the code ?
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));
Output
The output in the console: ?
tHE cASE of ThIS sTRINg wILL bE flIpPED
How It Works
The solution uses ASCII character codes to determine case and perform conversions:
- Uppercase letters (A-Z) have ASCII codes 65-90
- Lowercase letters (a-z) have ASCII codes 97-122
- The difference between uppercase and lowercase is 32
- Non-alphabetic characters remain unchanged
Alternative Method Using Built-in Methods
JavaScript provides simpler built-in methods for case conversion:
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();
}
return char;
}).join('');
};
const testStr = 'Hello World! 123';
console.log(flipCaseSimple(testStr));
hELLO wORLD! 123
Conclusion
Case flipping can be achieved using ASCII character codes or built-in string methods. The ASCII approach offers more control, while built-in methods provide cleaner, more readable code.
Advertisements
