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() or toLowerCase() 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.

Updated on: 2026-03-15T21:17:49+05:30

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements