How do I parse and evaluate a mathematical expression in a string?
<input type="text" id="expression_text" value="Enter equation.....">
var exp_string=$("#expression_text").val();
//"exp_string=4+6*9+3"
How do I parse and evaluate a mathematical expression in a string?
<input type="text" id="expression_text" value="Enter equation.....">
var exp_string=$("#expression_text").val();
//"exp_string=4+6*9+3"
Do not use eval()
, is just not save. Use a library like http://mathjs.org/ to accomplish your task.
I had some difficulty in understanding what you were after. As I understand it, you have a string that is a math assignment, that you want to return both the string and the calculated value to the backend.
There are several ways to do this. The obvious way if you have control over your inputs is to use eval()
, though a quicker version would be to avoid eval
and use a Function
constructor:
// I've replaced what would be returned by `val()` with the expected string
var text_input='exp_string=4+6*9+3'; //$("#expression_text").val();
// Performs the calculation and assigns the value to a global `exp_string` variable
Function(text_input)();
// Example of what can be used and what the variables hold
console.log(`${text_input} will equal ${exp_string}`);
Important!
I would be remiss if I did not bring attention to the security concerns regarding eval
or Function
contructor. As mentioned in the comments below, eval
is said to be "evil" for a reason. With lack of sanitation and control over inputs, it opens your front-end to dangerous XSS attack and other exploits. For this reason, it's better to be safe than sorry and shy away from its use.
That being said --and this is partially opinionated-- it isn't unusable. It serves a purpose and is efficient at what it does, but it is important to research the security risks and know when it is applicable.