Right now I have a variable which is storing a string.
var value = "66+88";
How can I replace '+' with a standard + operator so that I can evaluate
66 + 88 = 154
Thanks
Use String#split, Array#map it to get Number and then Array#reduce
var value = "66+88";
var result = value.split('+').map(Number).reduce(function(a, b) {
return a + b;
}, 0);
console.log(result);
You can use eval for this:
var value = eval("66+88");
But you need to be careful, especially if this string come's from user.
This function will evaluate input string as JavaScript and can damage your other scripts or can be used for hacker attacks.
Use it at your own risk!
eval?You could use split and reduce to sum up your string.
Here is an example.
var value1 = "66+88";
var value2 = "66+88+44";
function sumUpStr (strToSum) {
var sum = strToSum.split("+").reduce(function(prev, next) {
return +prev + +next;
});
return sum;
};
console.log("Sum of value1 is: " + sumUpStr(value1));
console.log("Sum of value2 is: " + sumUpStr(value2));
console.log("Sum of value1 + value2 is: " + sumUpStr(value1 + "+" + value2));