2

I need to perform calculation on dynamic string.

I will get an equation from db named rule through ajax. the rule may contain equation with operators like +,-,*,/,%.

how to perform this calculation?

  for (var i = 0; i < rules.length; i++) {
          var rule = rules[i].rule; // may contain $structurename1$*$structurename2$/$structurename3$ like this
          $('form :input[type="text"]').each(function(index,value){
              rule = rule.replace('$'+$(this).attr('structurename')+'$',$(this).val());
          });
  }

$('#result').val(rule);

2 Answers2

1

Calculate string value in javascript, not using eval

Using a combination of code from above link:

1. Strip anything in formula that thats not a number, parenthesis, OR operator.

2. evalulate formula as function

Modified to return NaN if the function errors due to invalid input. Which shouldn't happen due to the RegExp replacements in step 1.

function calc(fn) {
  var formula = fn.replace(/[^-()\d/*+.]/g, '');
  try {
    return new Function('return ' + formula)();
  } catch (err) {
    return NaN;
  }
}

DEMO: https://jsfiddle.net/tjywg716/

Community
  • 1
  • 1
Sean Wessell
  • 3,490
  • 1
  • 12
  • 20
-1
var str_expression=textbox1.text();
var result=eval(str_expression);
textbox2.text(result);
Tomasz Jakub Rup
  • 10,502
  • 7
  • 48
  • 49
Gianluca Paris
  • 1,391
  • 1
  • 14
  • 25