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.

2
  • use the eval() function Commented Oct 20, 2015 at 21:47
  • 1
    Eval is what you are looking for, but you should know its use is generally frowned upon. stackoverflow.com/questions/86513/… Commented Oct 20, 2015 at 21:49

3 Answers 3

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
Sign up to request clarification or add additional context in comments.

Comments

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.

1 Comment

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.
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>

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.