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
How to use case-insensitive switch-case in JavaScript?
To use case-insensitive switch-case in JavaScript, convert the input to either uppercase or lowercase before the switch statement. This ensures consistent comparison regardless of the original case.
Syntax
let input = userInput.toUpperCase(); // or toLowerCase()
switch (input) {
case 'OPTION1':
// Handle case
break;
case 'OPTION2':
// Handle case
break;
default:
// Default case
}
Example: Using toUpperCase()
Convert the input string to uppercase before switching:
<!DOCTYPE html>
<html>
<body>
<h3>Case-Insensitive Switch Example</h3>
<p id="result"></p>
<script>
var str = "amit";
str = str.toUpperCase();
let result = "";
switch (str) {
case 'AMIT':
result += "The name is AMIT<br>";
break;
case 'JOHN':
result += "The name is JOHN<br>";
break;
default:
result += "Unknown name<br>";
}
result += "Exiting switch block";
document.getElementById("result").innerHTML = result;
</script>
</body>
</html>
Example: Using toLowerCase()
Alternatively, convert to lowercase and use lowercase cases:
<!DOCTYPE html>
<html>
<body>
<h3>Case-Insensitive with toLowerCase()</h3>
<p id="output"></p>
<script>
var userInput = "JOHN";
var normalizedInput = userInput.toLowerCase();
let message = "";
switch (normalizedInput) {
case 'amit':
message = "Found Amit!";
break;
case 'john':
message = "Found John!";
break;
case 'mary':
message = "Found Mary!";
break;
default:
message = "Name not recognized";
}
document.getElementById("output").innerHTML = message;
</script>
</body>
</html>
Comparison of Approaches
| Method | Pros | Cons |
|---|---|---|
toUpperCase() |
Clear, widely used convention | Case labels must be uppercase |
toLowerCase() |
More readable case labels | Less common convention |
Key Points
- Always normalize the input before the switch statement
- Use either
toUpperCase()ortoLowerCase()consistently - Ensure all case labels match the chosen case format
- This approach works with user input, form data, and API responses
Conclusion
Case-insensitive switch statements require normalizing input with toUpperCase() or toLowerCase(). This ensures reliable string matching regardless of the original input case.
Advertisements
