0

How will i convert this string consist of two or more numbers and a arithmetic operator into integers with working operators. I trying for a while

let a = "45+55";
console.log(parseInt(a));

I want the answer with addition but it prints the first value.

Expected value

//100

Value i am getting

//45

Can anybody help?

Aman Kumar
  • 13
  • 2

2 Answers2

0

The eval() will execute a String. it will fork a new thread and Interpret Commands presented in String You can use it like this:

eval("45+55")
Abilogos
  • 4,777
  • 2
  • 19
  • 39
Aman Kumar
  • 13
  • 2
0

your issue can be resolved using eval, but as Hassan has already mentioned, eval can be very trick.

What you can do is create a function that parses the strings and does the operation:

function arithmetic(str) {
    // Probably want to remove all spaces here, but I won't do that now lol

    // Get the numbers based on whether there's a `+-/*` in the string
    const numList = str.split(/[+-/*]/i);
    const num1 = parseFloat(numList[0]);
    const num2 = parseFloat(numList[1]);

    // Create the regex to find the arithmetic operator
    const regex = new RegExp(/[+-/*]/i);

    // Run the correct operation on the numbers
    switch(regex.exec(str)[0]) {
        case '+':
            console.log(num1 + num2);
            break;
        case '-':
            console.log(num1 - num2);
            break;
        case '/':
            console.log(num1 / num2);
            break;
        case '*':
            console.log(num1 * num2);
            break;
        default:
            console.error('Operation not found');
            break;
    }
}

You can even extend this code to do more complicated math, but hey that's up to you and whether you want to.

Kitanga Nday
  • 3,517
  • 2
  • 17
  • 29