Given a string:
var str1 = "25*5+5*7";
Without using eval
or the constructor function in JavaScript, how would I be able to write a function called "output" that takes in the string and outputs the arithmetic value of the string, which in this case is 160?
You can use the expression parser of math.js:
Here's a full precedence expression evaluator following the recursive parsing idea I linked-to in a comment on the OP's question.
To do this, first I wrote a simple BNF grammar for the expressions I wanted to process:
This by itself requires a bit of experience to do simply and straightforwardly. If you have no experience with BNF you will find it incredibly useful for describing complex streams of items like expressions, messages, programming langauges, ...
Using that grammar, I followed the procedure outlined in the other message to produce the following code. It should be obvious that it is driven by grammar in a dumb mechanical way, and therefore pretty easy to write if you have that grammar.
(Untested. I'm not a JavaScript coder. This will surely contain a few syntax/semantic hiccups. Took me at about 15 minutes to code.)
It is straightforward to code such parsers/evaluators. See my SO answer on how to build a parser (which links to how to how to build an evaluator).
This is a simple parser with * over + precedence. I've tried to make it as educational as possible. I'll leave it up to you to add division and subtraction. Or brackets, if you're particularly ambitious.
You can create a new script:
Or use event handler content attributes:
Note these approaches are unsafe and as evil as
eval
but uglier. So I don't recommend them.