Javascript inoperant case with regex

It seems that the case of the javascript switch is not like in the regex, since it works with static values, but I cannot get the expected answers using regex in the case statement.

Could you confirm that there is a limitation of the js-interpreter and offer work around (I do not mean the if-then blocks package)?

thanks

example (not giving the expected answer, for example "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> 
+4
source share
2 answers

Your tests really aren't switchable. If necessary, 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); 
+9
source

You can also use a triple for this (but see disclaimer here ):

 var testme = "pwd_foo", response = testme === 'pwd' ? 'case1' : /^pwd.+/.test(testme) ? 'case2' : 'do something else'; 
+1
source

All Articles