0

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

Hardik Shah
  • 4,042
  • 2
  • 20
  • 41
Rohan
  • 11
  • 1
    Please share with us what you have tried – Ethan Vu Jul 18 '19 at 11:40
  • Welcome to Stack Overflow! Please share what you have already tried. Did you already write some code and did you get stuck on a specific part? Please remember Stack Overflow is not a code writing service! – Mathyn Jul 18 '19 at 11:41
  • 1
    Possible duplicate of [Evaluating a string as a mathematical expression in JavaScript](https://stackoverflow.com/questions/2276021/evaluating-a-string-as-a-mathematical-expression-in-javascript) – Mihai Iorga Jul 18 '19 at 11:48
  • Try [math.js](https://mathjs.org/). – Wyck Jul 18 '19 at 12:48

4 Answers4

0

Use Eval function :

eval(expression)

console.log(eval("1+5-8+9+4+6"))
console.log(eval("1+5-8+9*6"))
shrys
  • 5,860
  • 2
  • 21
  • 36
Shubham Verma
  • 4,918
  • 1
  • 9
  • 22
0

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
Nick Parsons
  • 45,728
  • 6
  • 46
  • 64
0

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);
})
Thomas
  • 11,958
  • 1
  • 14
  • 23
0

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);
}
Hardik Shah
  • 4,042
  • 2
  • 20
  • 41