如何从字符串中提取方程并求解,然后用javascript将答案放回字符串中



所以我有一个变量,让我们调用它,方程。在这种情况下,它是一个字符串;5+10";。如何编写一些代码来解决这个问题,然后将其放回字符串中打印回用户?

这可能有助于

function Calculate(){
var n1 = document.getElementById("n1").value
var n2 = document.getElementById("n2").value
var op = document.getElementById("op").value
var ans = document.getElementById("one_answers")

switch(op){
case '+':
ans.value = parseFloat(n1) + parseFloat(n2);
break;
case '-':
ans.value = parseFloat(n1) - parseFloat(n2);
break;
case '*':
ans.value = parseFloat(n1) * parseFloat(n2);
break;
case '/':
ans.value = parseFloat(n1) / parseFloat(n2);
break;
default:
ans.value = "Invalid Operator";
break;
}
}
<p><input type="number" id="n1" style="text-align:center;" placeholder="Enter 1st Number" minimum="0" value="0"  oninput="Calculate()" > 
<input type="string" max-length="1" id="op" size="5px" style="text-align:center;" placeholder="Operator"  oninput="Calculate()"> 
<input type="number" id="n2" oninput="Calculate()" placeholder="Enter 2nd Number" minimum="0" value="0" style="text-align:center;" ></p>
<input type="disabled" id="one_answers"  placeholder="Answer" style="text-align:center;" >

最新更新