How to turn a string into an evaluated expression in JavaScript?

twitter logo github logo ・1 min read

I am making my programming language 'Janky',
and I wanted to parse Integer values so I did this:

if(parseFloat(tok)) {
    values.push(parseFloat(tok))
    lastValue = parseFloat(tok)
    tok = ""
}

but in my language I want something like:

b = 1+2+3
c = b-3
//etc...

but I need some kind of

Math.parse()

or

parseMath()

function, is there anything like this in JavaScript?
Please let me know what I can do if there isn't....
Thanks!
Cheers!

twitter logo DISCUSS (6)
markdown guide
 

A number of years ago I created a little library to parse chemical formulas called mathy that can take equations and variables to then evaluate the output.

The way I did it was to build up the abstract syntax tree (AST) and then execute each of the operators as required (it starts here in the code).

If your goal is to just get the values, you can use eval or the Function constructor:

const fn = new Function('b = 1+2+3;c = b-3');

fn();
console.log(b, c); // 6 3

That just make a new function that is evaluated like any other chunk of code and because of how JavaScript works we created two global variables, b and c that contained the output of their respective formulas (you could put a var or let or const in front of them to control scope, I'm just following the post sample).

If you're wanting to get the formula as something that you can inspect, then you'll need to do some form of tokenization to generate the AST that you can evaluate.

 
 

I think eval() is what you are looking for. developer.mozilla.org/en-US/docs/W... But this be a security risk since it works for executing any string as JavaScript code, so you will want to make sure that user-inputted strings are validated as a mathematical expression before using eval() on them. There may also be another way to achieve the same end result without eval(), but I'm not sure about how the program will operate.

 

If eval doesn't satisfy your needs, you might want to check the library MathJS, though I'm not sure how much safer their Math.evalutate is and it's probably overkill.

 
 

I've also written my own language and the experience was incredible.
The best way you can solve this is using RegEx and implement your own way of how you wanna handle the input.

Classic DEV Post from Nov 7

What Are the Most Important CS Principles to Learn as a New Dev from a Non-Traditional Background?

PDS OWNER CALIN (Calin Baenen) profile image
I am a 13 (as of Oct 30 of 2019) yr/o developer who makes projects in languages like: Java, HTML, Python, JS, CSS, C, and am working on learning C++, and C#.
Join dev.to

If crime-fighting half-man/half-sharks can do it, so can you.