How can I convert a string into a math operator in javascript [duplicate]
If I've got a string that is a mathematic equation and I want to split it and then calculate it. I know I can use the eval() function to do this, but I'm interested if there's an alternative way to do this - specifically by splitting the strings first. So I've got something like
var myString = "225 + 15 - 10"
var newString = myString.split(" ");
This would turn myString into an array:
["225", "+", "15", "-", "10"];
My next task is to turn all the odd-numbered strings into integers, which I think I could use parseInt(); for. My question is, how do I turn the "+" and "-" into actual arithmetic operators? So that at the end I am left with a mathematic expression which I can calculate?
Is this possible?
var math_it_up = {
'+': function (x, y) { return x + y },
'-': function (x, y) { return x - y }
};
math_it_up['+'](1, 2) == 3;
JavaScript's eval
function was mentioned in a comment by Oliver Morgan and I just wanted to flush out how you could use eval
as a solution to your problem.
The eval
function takes a string and then returns the value of that string considered as a math operation. For example,
eval("3 + 4")
will return 7 as 3 + 4 = 7.
This helps in your case because you have an array of strings that you want you want to treat as the mathematical operators and operands that they represent.
myArray = ["225", "+", "15", "-", "10"];
Without converting any of the strings in your array into integers or operators you could write
eval(myArray[0] + myArray[1] + myArray[2]);
which will translate to
eval("225" + "+" + "15");
which will translate to
eval("225 + 15");
which will return 240, the value of adding 225 to 15.
Or even more generic:
eval(myArray.join(' '));
which will translate to
eval("225 + 15 - 10");
which will return 230, the value of adding 15 to 225 and substract 10. So you can see that in your case it may be possible to skip converting the strings in your array into integers and operators and, as Oliver Morgan said, just eval
it.