Chris
Chris

Reputation: 21

Using a String / text input field as a condition in a JavaScript if statement

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.

Upvotes: 2

Views: 2878

Answers (3)

Joe
Joe

Reputation: 82594

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.

Upvotes: 0

Bengel
Bengel

Reputation: 1053

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

Upvotes: 0

Stefan Kendall
Stefan Kendall

Reputation: 67812

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"); 
}

Upvotes: 2

Related Questions