What regular expression I need to use to correct
if (text.indexOf("+") != -1) {
action = "+";
} else if (text.indexOf("-") != -1) {
action = "-";
} else if (text.indexOf("*") != -1) {
action = "*";
} else if (text.indexOf("/") != -1) {
action = "/";
}
this code
?
EDIT:
and how can I improve this code:
switch (action) {
case "+":
result = parseInt(array[0]) + parseInt(array[1]);
break;
case "-":
result = parseInt(array[0]) - parseInt(array[1]);
break;
case "*":
result = parseInt(array[0]) * parseInt(array[1]);
break;
case "/":
result = parseInt(array[0]) / parseInt(array[1]);
break;
default:
break;
}
Sorry for dull questions I am new in js.
You can use either of these:
If there’s the possibility of newlines in your
textthen change the first to:Edit: You can improve your
switchstatement by using, e.g.For more details on why
parseIntis probably bad, see this answer.You can also remove the superfluous
defaultsection of your case statement. However, I suspect that your desired “improvement” was making fewer lines. Given that=-*/are operators in JavaScript (and not methods), I cannot think of any way to avoid having four calculations (i.e. aswitchorif/else if).Whereas in Ruby you could, for example, use
array[0].send(action,array[1])to cover all four cases 😉