PhoxKiD PhoxKiD - 10 days ago 6
Javascript Question

Parse linear equation in Javascript

For example: if

2x + 1
is given as a string, how to use it in a function.

Say
x = 3
then we should get
2 * 3 + 1 = 7
.

Answer

Try like this: use eval() .

Note: its only on '2x+1' static equation not for all.

function calc() {
    var str = document.getElementById('input').value;
    var obj = document.getElementById('obj').value;
    str = str.replace('x', '*' + obj)
    console.log(str)
    console.log(eval(str))
 }

calc();
Str:<input  id="input" value="2x+1"><br />
x:<input id="obj" type="number" value="3">
<button onclick="calc()">Evaluate</button>

Comments