Home » Javascript » check validation of logical expression in javascript

check validation of logical expression in javascript

Posted by: admin November 1, 2017 Leave a comment

Questions:

I want to check if a string contains a valid expression or not in javascript, regex will also work

Input valid string – ((c1 and c2) or c3) and c4
Input invalie string – (c1 and c2) or) c4 and

Answers:

This is kinda a fun way:

If You have a string like:

var str = 'true && true'

you can create a function out of it:

var fn = new Function('return ' + str);
fn(); // returns true

Anything that would be invalid would fail when creating the function.