I have a string like this:
var data ="(1+2*(3+2))";
I m trying to parse the string, to the get the appropriate result. But still i didn't get any solution, any ideas ?
Expected result = 11
try
var result = eval(data);
though eval can be evil, it's not always the case
As long as you are 100% sure that the input is absolutely safe, you can directly use eval:
var data ="(1+2*(3+2))";
var res = eval(data);
If you don't trust the input, however, you can think about finding a different solution (by still using eval), like proposed by the user Kennebec here:
Or even better, you can think about using a third-party library, like mathjs:
The reason why you shouldn't be using eval are actually many, but as long as your sure that you can control the flow of your input and as long as you are absolutely sure that the user cannot use eval for any evil scope you are also safe to use eval.
In any case, because mathjs exists, if you're going to need further calculation I personally recommend you mathjs.
In the case of mathjs, the code would be something like this:
var data ="(1+2*(3+2))";
var res = math.eval(data);
fiddle: http://jsfiddle.net/jLxkn7no/
Also, as a side note, to use the mathjs library you simply have to include a single script, and it is available as a cdn: http://cdnjs.com/libraries/mathjs
EDIT:
If you're not a DL;DR; reader, feel free to read below:
If you're curious about what is the difference between the regular eval() mathjs's eval, here is the snippet taken directly from the source code:
/**
* Parse and evaluate the given expression
* @param {String} expr A string containing an expression, for example "2+3"
* @return {*} result The result, or undefined when the expression was empty
* @throws {Error}
*/
Parser.prototype.eval = function (expr) {
// TODO: validate arguments
return _parse(expr)
.compile(math)
.eval(this.scope);
};
and _parse:
/**
* Parse an expression. Returns a node tree, which can be evaluated by
* invoking node.eval();
*
* Syntax:
*
* parse(expr)
* parse(expr, options)
* parse([expr1, expr2, expr3, ...])
* parse([expr1, expr2, expr3, ...], options)
*
* Example:
*
* var node = parse('sqrt(3^2 + 4^2)');
* node.compile(math).eval(); // 5
*
* var scope = {a:3, b:4}
* var node = parse('a * b'); // 12
* var code = node.compile(math);
* code.eval(scope); // 12
* scope.a = 5;
* code.eval(scope); // 20
*
* var nodes = math.parse(['a = 3', 'b = 4', 'a * b']);
* nodes[2].compile(math).eval(); // 12
*
* @param {String | String[] | Matrix} expr Expression to be parsed
* @param {{nodes: Object<String, Node>}} [options] Available options:
* - `nodes` a set of custom nodes
* @return {Node | Node[]} node
* @throws {Error}
*/
math.parse = function parse (expr, options) {
return _parse.apply(_parse, arguments);
}
};