Alisha Sharma
Alisha Sharma

Reputation: 149

convert string to boolean and compare with if condition in js

I have an attribute where I have got condition .I took that condition from tag's attribute now I want place that condition in if block and get result.

my code:-

 <div myCondition="1 == 2" id="hey"></a>
 <script>
  var a = document.getElementById('hey');
  var x = a.getAttribute('myCondition');
  if(x){
    console.log('accepted')
  }else{
    console.log('not accepted')
  }
</script>

above program should return not accepted value of myCondition attribute can be very complex for example:-

'hello' == 'hello'
 5>1  etc

Upvotes: 0

Views: 443

Answers (1)

Farzad Abdolhosseini
Farzad Abdolhosseini

Reputation: 360

I guess what you need is the eval function. As it says in the provided link:

The eval() function evaluates JavaScript code represented as a string.

So, you can change your code like this:

if( eval(x) ){
  console.log('accepted')
}else{
  console.log('not accepted')
}

P.S: That being said, I don't think doing it like this really safe.

Upvotes: 1

Related Questions