learningjavascriptks learningjavascriptks - 1 month ago 6
Javascript Question

How do I execute a math operation from a string with brackets?

I am having a hard time executing math with brackets like

7( 7+(7 (7+1) ))(7)
. I am doing
eval()
on my operations. I thought to solve this is to convert this to
7*(7+(7*(7+1)))*(7)
. I tried

/(?!\*\()(\()/g


to avoid
'*('
on regexp and accept
'('
for replace method, but I fail. I am thinking of inserting
*
before
(
. How can I run
7( 7+(7 (7+1) ))(7)
properly? I am doing this for a calculator project.

Answer

This is a non regex solution. First replace all spaces with empty strings. Then replace the "(" with "*(" only if the parentheses is not preceded by an operator.

var testString = ("7( 7+(7 (7+1) ))(7)").split("").filter((e) => e!=" ");
var arr = ["+", "-", "/", "("];

var resultString = testString.reduce(function(prev, curr, i)                               
 {
     if(arr.indexOf(i-1 ? testString[i-1] : "test") && curr == "(") { 
           return prev += "*(";
       }else{
           return prev += curr;
        }
        
  },"");

console.log(resultString);