Reputation: 8183
I have a string expression like such: "1+2+3"
, and it must stay as a string. In other words, looping and casting the digits to perform the operation isn't an option, so my solution is eval("1+2+3")
. But eval()
is slow and has all these issues associated with it. Is there an alternative to evaluate my string?
Upvotes: 0
Views: 867
Reputation: 82654
This is a silly question:
var reducer = function (a, b) {
return +a + +b;
};
"1+2+3".match(/[+-]?\d+/g).reduce(reducer); // 6
// or addition only
"1+2+3".split(/\D/).reduce(reducer); // 6
Upvotes: 0
Reputation: 77089
Evaluating a string is not only slow, it's dangerous. What if, by malicious user intent or error, you end up evaluating code that crashes your program, destroys your data o opens a security hole?
No, you should not eval()
the string. You should split it, cast the operands to numbers, and sum them.
You can keep the string
around if you like (you said you needed the string), but using the string
to actually perform this operation is a Really Bad Idea.
var string = "1+2+3"
var numbers = string.split('+').map(function(x) { return parseInt(x) })
var sum = numbers.reduce(function(total, x) { return total + x }, 0)
Upvotes: 2