+ 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...
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;
}
+ 9
one by one đ
http://www.cprogramming.com/tutorial/lesson5.html
+ 7
thanks you really helped me
+ 5
đ
đ
đ
I don't find what I want ^^ I think we need to use the regex, no ?