2

I am trying to allow for a if statement condition to be placed into a text field and then for Javascript to take that text field and return if it would be true or false.

logicStr = document.getElementById('logicString').value;

if(logicStr){
alert("true");
}else{
alert("false"); 
}

with the example above if the input was "1 == 0" the alert should be false. But Javascript is seeing it as me asking is the string not null and it isnt so it alerts true. I need to somehow convert to a logic boolean statement.

3 Answers 3

2

So long as this is all driven by user input and retained locally, eval should work for you.

if(eval(logicStr)){
   alert("true");
}else{
   alert("false"); 
}
Sign up to request clarification or add additional context in comments.

Comments

0

Look into the JavaScript eval() function. It takes a string input and will evaluate it as a JavaScript expression.

eval("1==0");
false

eval("1==1"):
true

Comments

0

Demo

'false === false'.replace(/([a-zA-Z0-9]+) ?(==={0,1}) ?([a-zA-Z0-9]+)/, function (str,b,c,d) {
   if (/false/.test(b)) b = false;
   if (/false/.test(d)) d = false;
   if (/true/.test(b)) b = true;
   if (/true/.test(d)) d = true;

   if (c == '===') return +b === +d;
   else return d == b;
}); // true

'1 == 0'.replace(/([a-zA-Z0-9]+) ?(==={0,1}) ?([a-zA-Z0-9]+)/, function (str,b,c,d) {
   if (/false/.test(b)) b = false;
   if (/false/.test(d)) d = false;
   if (/true/.test(b)) b = true;
   if (/true/.test(d)) d = true;

   if (c == '===') return +b === +d;
   else return d == b;
}); // false

attempt to parse it.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.