4

It looks like the javascript switch case doesn't like the regex as a case as it works with static values but I can't get the expected answers using regex in the case statement.

Would you pls confirm that limitation of the js interpretor and propose a work around (I mean not a if-then blocks suite) ?

Thx

example (not giving the expected answer ,eg 'case3') :

<script type="text/javascript">
var testme = "pwd_foo";
var response = false;
var reg = /^pwd.+/;

switch (testme) {
case 'pwd':
    response = 'case1';
    break;
case reg.test:
    response = 'case2';
    break;
case /^pwd.+/:
   response = 'case3';
   break;
default:
    response = 'do sthg else';
}

alert('reg test: ' + reg.test(testme)+'\nresponse:' + response);
</script>
hornetbzz
  • 9,188
  • 5
  • 36
  • 53

2 Answers2

9

Your tests do not really lend themselves to a switch. If you must, you can do this which is NOT RECOMMENDED:

DEMO HERE

var testme = "pwd_foo", response;
var reg = /^pwd.+/;

switch (true) {
case testme=='pwd':
    response = 'case1';
    break;
case reg.test(testme):
    response = 'case2';
    break;
default:
    response = 'do sthg else';
}

alert('reg test: ' + reg.test(testme)+'\nresponse:' + response);
mplungjan
  • 169,008
  • 28
  • 173
  • 236
1

You can also use a ternary for this (but do see the disclaimer here):

var testme = "pwd_foo", 
    response = 
       testme === 'pwd' 
         ? 'case1' 
         : /^pwd.+/.test(testme) 
           ? 'case2' 
           : 'do something else';
Community
  • 1
  • 1
KooiInc
  • 119,216
  • 31
  • 141
  • 177
  • thx but that's not what I was looking for, as my question is trying to simplify the real case I need. No doubt, I need a switch case for my particular purpose. I used the switch(true) which works like a charm. – hornetbzz Jul 05 '11 at 10:07
  • That's ok. It's just a demonstration of an alternative and a little teaser for @mplungjan who in a previous life demonstrated an aversion for ternaries (and the `switch(true)` construction for that matter) – KooiInc Jul 05 '11 at 11:37