Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make a function that can convert any string that looks like javascript code to objects?

Being new to javascript, I have a question. Lets, consider a string that looks like this :

 var str = "Math.random() > 0.5";

Now lets have some javascript :

  console.log( turnUp( str ) ); // true or false

So, turnUp() is just a function I assumed can do something like this :

Without turnUp() :

 console.log( str );
 // Is equivalent to console.log( "Math.random() > 0.5" );

Output :

 Math.random() > 0.5

With turnUp() :

 console.log( turnUp( str ) );
 // Is equivalent to console.log( Math.random() > 0.5 );

Output :

 true

Or

Output :

 false

So, with the help of examples, you might understand what I need ! So, how to make the turnUp() function ?

Thanks In Advance

like image 449
Gaming King Avatar asked Mar 09 '26 14:03

Gaming King


1 Answers

eval() has many drawbacks so I prefer you to do something like this :

 var turnUp = function(str) {
    return Function(' "use strict"; return (' + str + ') ')();
  }

Now you can do :

 var str = "Math.random() > 0.5";

 console.log( str ); // => Math.random > 0.5
 console.log( turnUp( str ) ); // => true or false
like image 52
Debarchito Avatar answered Mar 12 '26 04:03

Debarchito