-2

I am getting a string back "1+2" and would like to remove the "+" and then add the numbers together. Is this possible using Regex? So far I have:

let matches = pattern.exec(this.expression);
matches.input.replace(/[^a-zA-Z ]/g, "")

I am now left with two numbers. How would I add together?

"this.a + this.b"

user992731
  • 3,400
  • 9
  • 53
  • 83

3 Answers3

2

Assuming the string returned only has '+' operation how about:

const sum = str.split('+').reduce((sumSoFar, strNum) => sumSoFar + parseInt(strNum), 0);
ssbarbee
  • 1,626
  • 2
  • 16
  • 24
1

You cannot add two numbers using regex.

If what you have is a string of the form "1+2", why not simply split the string on the + symbol, and parseInt the numbers before adding them?

var str = "1+2";
var parts = str.split("+"); //gives us ["1", "2"]
console.log(parseInt(parts[0]) + parseInt(parts[1]));
Anis R.
  • 6,656
  • 2
  • 15
  • 37
0

If you don't always know what the delimiter between the two numbers is going to be you could use regex to get your array of numbers, and then reduce or whatever from there.

var myString = '1+2 and 441 with 9978';
var result = myString.match(/\d+/g).reduce((a,n)=> a+parseInt(n),0);
console.log(result); // 1 + 2 + 441 + 9978 = 10422

*Edit: If you actually want to parse the math operation contained in the string, there are a couple of options. First, if the string is from a trusted source, you could use a Function constructor. But this can be almost as dangerous as using eval, so it should be used with great caution. You should NEVER use this if you are dealing with a string entered by a user through the web page.

var myFormula = '1+2 * 441 - 9978';
var fn = new Function('return ' + myFormula);
var output = fn();
console.log(myFormula, ' = ', output); //1+2 * 441 - 9978  =  -9095

A safer (but more difficult) course would be to write your own math parser which would detect math symbols and numbers, but would prevent someone from injecting other random commands that could affect global scope variables and such.

David784
  • 7,031
  • 2
  • 22
  • 29
  • What if I am multiplying, dividing or subtracting? – user992731 Feb 13 '20 at 19:47
  • @user992731 That means another question. You asked how to *Remove calculator operations, keep numbers and then **add together** using regex* – Wiktor Stribiżew Feb 13 '20 at 20:06
  • 1
    @user992731 I've updated my answer to reflect a couple of ways to do this. It would have been helpful if you had stated this in your original question. – David784 Feb 13 '20 at 20:53