0

I am making a calculator in JavaScript and I want to know how to turn a string into an expression.

var numbers = "5+5+6";
numbers = +numbers;
 document.querySelector('.screen').innerHTML = numbers;

Adding + before the variable does not seem to work. I would appreciate it if someone helped.

Joe Clark
  • 1
  • 1
  • use the eval() function – Typo Oct 20 '15 at 21:47
  • 1
    Eval is what you are looking for, but you should know its use is generally frowned upon. http://stackoverflow.com/questions/86513/why-is-using-the-javascript-eval-function-a-bad-idea – Matt R Oct 20 '15 at 21:49

3 Answers3

1

You can use the eval() function like this:

var numbers = "5+5+6";
document.querySelector('.screen').innerHTML = eval(numbers);;

Evaluate/Execute JavaScript code/expressions:

var x = 10;
var y = 20;
var a = eval("x * y") + "<br>";
var b = eval("2 + 2") + "<br>";
var c = eval("x + 17") + "<br>";

var res = a + b + c;

The result of res will be:

200
4
27
nem035
  • 34,790
  • 6
  • 87
  • 99
Typo
  • 1,875
  • 1
  • 19
  • 32
0

Without using eval, which is cheating - you could always write a simple calculator app.

First, take advantage of String.split() as follows

var numbers = "5+5+6";

numbers.split("");
// => ["5","+","5","+","6"]

Now all you need to do is figure out how to evaluate it while keeping the order of operations correct. Hint: it might involve trees.

Jonah Williams
  • 20,499
  • 6
  • 65
  • 53
  • 1
    First of all, saying it *might* involve trees isn't really a hint and secondly it doesn't even need trees. The OP should know that he needs to convert this `infix` notation to `postfix` and then use a postfix evaluation algorithm to perform the calculation. – nem035 Oct 20 '15 at 21:56
0

Try using String.prototype.match() , Array.prototype.reduce() , Number() . See also Chrome App: Doing maths from a string

var numbers = "5+5+6";
var number = numbers.match(/\d+|\+\d+|\-\d+/g)
  .reduce(function(a, b) {
    return Number(a) + Number(b)
  });
document.querySelector(".screen").innerHTML = number;
<div class="screen"></div>
Community
  • 1
  • 1
guest271314
  • 1
  • 15
  • 104
  • 177