Hello.

It is necessary to calculate the string. Implemented through new Function(str) . The question is: from a security point of view, is it enough to check the method (function) and the absence of assignment operations with a regular check?

 var evalute = function (expr, context) { expr = expr.replace(/\s+/g, ''); if (/[^^\+\-\*\/\<\>\=]\(|[^\<\>\!\=]\=[^\=]/.test(expr)) { throw new Error('bad expression '+expr); } return (new Function('return ' + expr).bind(context))(); }; 
  • one
    Calculate the arithmetic expression need? Like 2 + 7? This kind of hack does not scare? var arr = [1,2,3]; console.log (evalute ("this.length -", arr), arr); - zb '12
  • Operators -!, +, -, /, *, <,>,> =, <=. There is no need for methods, so I "banned" them from harm's way. Operations carried out on strings, numbers, objects, Boolean values. - alvoro
  • Examples of expressions that you are going to run, show. - zb '
  • @eicto, yes, this is trouble. About doubleplus and minus forgot. - alvoro
  • Well, I'm talking about what I say ... I think the idea itself is not very good. There is a lot you can forget about, if you need to calculate arithmetic in this way, then it is probably better to parse honestly, for example, a library that may suit you mathjs.org/docs/index.html - zb '12

1 answer 1

Well, I'm telling you - save on bytes (and not on your own) - lose somewhere safe or accurate, what's the problem?

 npm install mathjs 

and do something more interesting than the invention of a lisopedist (as a result, you still write a parser, after a dozen bug reports).

And for people unfamiliar with programming, it is necessary to write hard-bound interfaces.