Yeah, thanks mate. That was the conclusion i’d come to. It would be tidier to use switch, as i need to add another ‘case’ to an existing ‘switch’ statement. But i guess it could just fall through and get caught by an ‘if’ statement.
Realistically, though, it’ll probably mean i’ll have to rewrite the whole ‘switch’ block to maintain consistency…
JavaScript actually allows the cases to be any object so Regular Expressions there are perfectly valid (unlike in many other languages where what you can use as the case is more limited).
It may be “valid”, but it doesn’t appear to actually work (at least not in Firefox, anyway). I’ve tried with a regexp literal and a ‘new regexp’ object and it doesn’t match.
Can you give an example of a construct where it does work?
I think the switch statement evaluates (switchexp == caseexp), so using a regex as a caseexp does not work as intended - it tests if the switchexp IS the regex instead of if the regex matches the switchexp. You could try:
switch (true) {
case re1.test(s):
statement
break;
case re2.test(s):
statement
break:
…
}
I imagine that switchexp is evaluated when entering the switch case block and that each caseexp is evaluated in turn until one is found that evaluates to the same thing as the switchexp. All following caseexp should not be evaluated.
A switch actually performs === tests not == tests. The fields have to be the same type as well as the same values.
You are right though as to why it wouldn’t work - for the case to match the value to compare it with would need to be an identical regular expression and not a string that satisfies the expression.