The function you’re in need of is eval()
.
eval('1+1');
// Output: 2
Or implemented in your code that would be:
var equation = document.getElementById("equation").value;
var answer = document.getElementById("answer");
answer.innerHTML = eval(equation);
For more on the eval()
function, read the documentation.
As noted, eval
is not very secure. It’d be easy to say, “hey, it’s on the client so what do I care.” And, you might be right. But, depending on your exact use case, you could be opening your users up to cookie theft and all sorts of undesirable things.
If you really need to do this in production, you’ll likely want to use a sandbox with Node. VM2 should give you what you need.
So I have this bit of code for a calculator and it when I put something in the textbox, it only shows undefined. I need it when I put a mathematical expression like 1+1 it will show 2. You can see it in action in my website: G1blue.github.io/gencal.html
<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8">
<title>Calculator: General (Under maintenance)</title>
<style>
h1{
font-size: 100px;
margin: auto;
}
div {
font-size: 100px;
position: absolute;
top: 150px;
}
</style>
</head>
<button><a href="index.html">Go to home</a></button>
<body>
<h1>Calculator: General</h1>
<input oninput="varChange()" id="equation" type="number">
<div id="answer"></div>
<script>
function varChange(){
var equation = document.getElementById("equation").value;
var answer = document.getElementById("answer");
answer.innerHTML = new Function(equation)()
}
</script>
</body>
</html>
How do you fix this?
No problem. If you found this answer helpful, please consider marking it as an accepted answer!
Using eval is very dangerous, because this makes the site trivially easy to conduct XSS attacks on. I personally would recommend building a parser instead, which gives much more freedom. However, if you insist on
@KennethLew is right. From a security point of view I would not recommend