To make your JavaScript switch statements more dynamic and flexible, you can use regular expressions (RegExp). Here are the various ways to use RegExp in switch case statement.
1. Using test() Method in switch
The test() method can be used to check if a string matches a given regular expression. Let’s see how this works with a simple switch statement.
OutputThe string contains 'hello'
- The switch expression evaluates true for each case.
- The test() method checks if the string input matches the regular expression (e.g., /hello/ or /world/).
- When a match is found, the corresponding case executes, and we print the matching message.
2. Using match() Method in switch
Alternatively, we can use the match() method, which returns an array of matched substrings or null if no match is found.
OutputThe string is a valid date format.
- We use the match() method to check if the input string matches a date format (\d{4}-\d{2}-\d{2}) or a phone number format (\d{3}-\d{3}-\d{4}).
- The match() method returns an array if a match is found, and the corresponding case is executed.
- If no match is found, the default case is executed.
3. Matching Complex Patterns (Email Validation)
Here’s how you can use a regular expression to validate an email address inside a switch statement.
OutputThe string is a valid email address.
- The regular expression /[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}/ matches a valid email format.
- If the input matches the email pattern, the message "The string is a valid email address" is printed.
- If no match is found, the default case will output "The string is not a valid email address."
4. Multiple Pattern Matches
You can also use switch to handle multiple patterns by chaining case blocks with different regular expressions.