How to convert string to boolean value?

  Kiến thức lập trình

Is it possible to convert/wrap an array value into a if statement? For clarification, the statement I received from my code is always a string in an array, and I want to execute it in an if block. Right now, it does not do a comparison because it is a string. So how can I convert a string into a statement that will be compared?

let counter = 11;
let statement = ['counter > 10']; // array string received from other code (always a string)

if(statement[0]) {
    // should be true
}

Result expected to be true, where the if statement is dynamically executed.

3

let counter = 11;
let statement = ['counter > 10']; // (always a string)

if (eval(statement[0])) {
    console.log("The statement is true");
} else {
    console.log("The statement is false");
}

New contributor

noraxx is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.

1

I think a better way to ask this question is “How to evaluate a string as if it were Javascript code. There is a way to do it in JavaScript using the eval method.

let counter = 11;
let statement = ['counter > 10']; // (always a string)

if (eval(statement[0])) {
      // should be true
}

However, I would really not recommend using this. It’s a huge security risk. Please use it only if you know what you are doing.

Referehce: https://www.w3schools.com/jsref/jsref_eval.asp

You may be able to use the math parser for this, though I’m not sure. It’ll depend on what kind of things you get back in that string.

// https://github.com/silentmatt/expr-eval/tree/master
// there may be other ways to do this, this is simple though
import Parser from 'expr-eval'; 

const options = {x:3};   //see the documentation

const parsedStatement = statement[0];
const result = Parser.evaluate(parsedStatement, {options});
console.debug('Expression Result: ', result);

LEAVE A COMMENT