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
Swapcase function in JavaScript
In JavaScript, a swapcase function converts uppercase letters to lowercase and lowercase letters to uppercase while leaving non-alphabetic characters unchanged.
Problem Statement
We need to create a function that takes a string and returns a new string where:
- Uppercase letters become lowercase
- Lowercase letters become uppercase
- Non-alphabetic characters remain unchanged
Method 1: Using Helper Function
This approach uses a separate function to determine the case of each character:
const str = 'ThIs Is A STriNG';
const findLetter = (char = '') => {
if (char.toLowerCase() === char.toUpperCase()) {
return char; // Non-alphabetic character
} else if (char.toLowerCase() === char) {
return char.toUpperCase(); // Lowercase to uppercase
} else {
return char.toLowerCase(); // Uppercase to lowercase
}
};
const swapCase = (str = '') => {
let result = '';
for (let i = 0; i
tHiS iS a stRIng
Method 2: Using Array Methods
A more concise approach using split(), map(), and join():
const swapCaseArray = (str) => {
return str.split('').map(char => {
if (char === char.toLowerCase()) {
return char.toUpperCase();
} else {
return char.toLowerCase();
}
}).join('');
};
const testString = 'Hello World 123!';
console.log(`Original: ${testString}`);
console.log(`Swapped: ${swapCaseArray(testString)}`);
Original: Hello World 123!
Swapped: hELLO wORLD 123!
Method 3: Using Regular Expressions
Using regex with replace() for a more functional approach:
const swapCaseRegex = (str) => {
return str.replace(/[a-zA-Z]/g, (match) => {
return match === match.toLowerCase() ?
match.toUpperCase() :
match.toLowerCase();
});
};
const examples = ['JavaScript', 'Hello123World', 'ABC def GHI'];
examples.forEach(example => {
console.log(`"${example}" ? "${swapCaseRegex(example)}"`);
});
"JavaScript" ? "jAVAsCRIPT"
"Hello123World" ? "hELLO123wORLD"
"ABC def GHI" ? "abc DEF ghi"
Comparison
| Method | Readability | Performance | Code Length |
|---|---|---|---|
| Helper Function | Good | Fast | Long |
| Array Methods | Excellent | Moderate | Short |
| Regular Expression | Good | Moderate | Very Short |
Key Points
- All methods preserve non-alphabetic characters (numbers, spaces, symbols)
- The helper function approach is most explicit about the logic
- Array methods provide a functional programming style
- Regular expressions offer the most concise solution
Conclusion
The swapcase function can be implemented in multiple ways in JavaScript. Choose the array method approach for readability, or the regex method for conciseness, depending on your team's preferences and coding standards.
Advertisements
