开发者

Javascript inoperant Switch Case with a regex

开发者 https://www.devze.com 2023-03-18 13:02 出处:网络
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.

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);


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';
0

精彩评论

暂无评论...
验证码 换一张
取 消