How to get the result of a string with numbers and add/sub/multiply operators in between
"1+5+6", "5-8+6", "1+5-8+9+4+6" ..etc
How to get the result of a string with numbers and add/sub/multiply operators in between
"1+5+6", "5-8+6", "1+5-8+9+4+6" ..etc
Use Eval function :
eval(expression)
console.log(eval("1+5-8+9+4+6"))
console.log(eval("1+5-8+9*6"))
You could use a function constructor/eval
if it is safe to do so like so:
const str = "1+5+6";
const res = (Function("return "+str))();
console.log(res); // 12
Or, instead, if you are only ever using the plus or minus operator in your string, I recommend you .split()
your string into an array, and then use .reduce()
to sum up each number like so:
const str = "1+5+6-1+2";
const res = str.split(/([+-]\d+)/).reduce((sum, n) => sum+ +n, 0);
console.log(res); // 13
For such simple equations you don't need evil (eval), or its little brother, the Function constructor. These formulas can be parsed and evaluated with just a few commands.
[
"1+5+6",
"5-8+6", "1+5-8+9+4+6"
].forEach(formula => {
const result = formula.replace(/\s/g, "") // remove whitespace (just in case)
.split(/(?=[+-])/) // split the string into numbers with their respective sign
.map(Number) // convert them into actual numbers
.reduce((a,b) => a+b); // get the sum of the numbers (positive and negative)
console.log(formula, "=", result);
})
Using split and reduce methods:
Below snippet will work for all +/- to any position.
const val1= "1+5+6";
const val2= "1+5+6-3-4+5+6-3-5";
const val3= "-1+5+6-1-3-8+1";
let lastSign = '';
console.log(LetsSum(val1));
console.log(LetsSum(val2));
console.log(LetsSum(val3));
function LetsSum(val) {
return val.split('').reduce((sum, ele, i) => {
if(isNaN(parseInt(val[i]))) {
lastSign = val[i];
} else {
sum = sum + +(lastSign+ele);
}
return sum;
}, 0);
}