Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript inoperant Switch Case with a regex

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>
like image 390
hornetbzz Avatar asked Dec 28 '22 17:12

hornetbzz


1 Answers

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);
like image 66
mplungjan Avatar answered Jan 10 '23 23:01

mplungjan