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>
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With