For example: if I have a string "10+5", can I somehow parse it and get 15 back? I'm building a calculator and the formula is a string (e.g. "2+1/5-9*3") and when I press equals I would like this string to become a number. Is this possible or should I approach this differently?
Asked
Active
Viewed 42 times
0
-
The shortest solution is making a new function and running it: `new Function( 'return 10+5;' )();` But then your problem becomes making sure the string is a valid JS expression and not some malicious code. So the better solution is building parsers that will split the string into it's components and use functions to perform those calculations, as shown in a bunch of the answers of the duplicate. – Shilly Sep 21 '18 at 13:50
-
@Shilly I'm not concerned about security as this is for a CodePen Pen, so could you elaborate a bit more on what you said? – GiaFil7 Sep 21 '18 at 13:54
-
1If you not concerned about security than `eval` will work :). Just `eval('10+5')`. But please don't use it in real projects – Andrey Sep 21 '18 at 13:56
-
This topic is closed, so we can't post any real answers. The `new Function();` I posted is a slightly safer version of `eval();` So if security is of no concern whatsoever, `const str = '10+5'; const result = new Function(\`return ${ str };\`)();` will work. Or even shorter, as Andrey suggest: `const str = '10+5'; const result = eval( str );`. – Shilly Sep 21 '18 at 14:00
-
@Shilly This topic is closed because it's already answered. The linked duplicate already contains your `new Function` comment, as well as several better solutions. – user229044 Sep 21 '18 at 14:48
-
@meager I know that. Just answering the OP's question since I was tagged. And I felt that my original comment was justified to explicitly state that `new Function()` also suffers from the same code injection issues `eval()` has. Which imho isn't completely clear in the duplicate unless you know that `new Function()` and `eval()` are (almost) the same. – Shilly Sep 21 '18 at 15:00