0

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"
Dharman
  • 30,962
  • 25
  • 85
  • 135
Sibin Rasiya
  • 1,132
  • 1
  • 11
  • 15
  • Just dont use `eval()` – void Feb 22 '18 at 05:02
  • 1
    Possible Duplicates: [Safe evaluation of arithmetic expressions in Javascript](https://stackoverflow.com/questions/5066824/safe-evaluation-of-arithmetic-expressions-in-javascript) or [Evaluating a string as a mathematical expression in JavaScript](https://stackoverflow.com/questions/2276021/evaluating-a-string-as-a-mathematical-expression-in-javascript) – Rajesh Feb 22 '18 at 05:06

2 Answers2

2

Do not use eval(), is just not save. Use a library like http://mathjs.org/ to accomplish your task.

Pablo
  • 5,897
  • 7
  • 34
  • 51
  • First, please read comments under vol7ron's answer. Second, suggesting a library can be a double edged sword. It can go against you. Third and more importantly, *only-link* answers are considered bad. Please try to explain how and why. – Rajesh Feb 22 '18 at 05:12
  • 3
    fourth - this doesn't answer the question. if i asked you how to add 2 plus 2 and you say, don't use a watermelon, that's a non-answer. – I wrestled a bear once. Feb 22 '18 at 05:17
1

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.

vol7ron
  • 40,809
  • 21
  • 119
  • 172