+ 6

Input autorisation

I did an input, and with a switch statment I did switch (cmd): case 'hello': break; etc... with a default and an "error : 'hi' isn't a valid command" (for example). how can I do a case 'x' + [a number between 1 and +infinite]: ? like this the user will can write 'x9' or 'x24' etc...

30th Aug 2017, 7:33 AM
NoxFly
NoxFly - avatar
4 Answers
+ 7
Switch-case structure aren't well suited for this kind of test... you rather will be advice to use Regular Expression (regex) with an if-else-if structure... re_x = /^x\d+$/gi; // regexp matching string starting (^) with 'x' and immediatly followed by one to any digits without anyelse before end ($)... ('i' is for case insentitive, 'g' is for group/multi-search -- not necessary in your present case) if (cmd=='hello') { ... } else if (cmd=...) { ... } else if (re_x.test(cmd)) { /* the command is 'x???' */ } else { /* default case -- invalid command */ } ... but however, you can also test for regex inside your default switch case, if you want it absolutly: switch (cmd) { case 'hello': break; case default: if (re_x.test(cmd)) { ... } else if (...) { ... } // how many cases you want else { /* default case -- invalid command */ } //break; }
30th Aug 2017, 7:57 AM
visph
visph - avatar
30th Aug 2017, 7:39 AM
jay
jay - avatar
+ 7
thanks you really helped me
30th Aug 2017, 8:03 AM
NoxFly
NoxFly - avatar
+ 5
😅😅😅 I don't find what I want ^^ I think we need to use the regex, no ?
30th Aug 2017, 7:50 AM
NoxFly
NoxFly - avatar