How do I convert a string into an executable line of code in Javascript?

后端 未结 5 618
盖世英雄少女心
盖世英雄少女心 2020-12-09 09:48

I have the following bit of code

console.log(\"I am\");

var x = \"console.log(\'Alive!\')\";

Now I only want to use x to exec

5条回答
  •  佛祖请我去吃肉
    2020-12-09 10:19

    What you are looking for is eval(). By passing a string to this function you will evaluate the string as JavaScript code and it will return whatever return-value the code in the string returns.

    Be aware when using this function though. You do not want to evaluate any code you do not know is safe to execute. For example, running user-generated code could mess up whatever you are making. While using this in JavaScript on a website this will probably only cause issues on the client-side and hence probably won't be much of a security threat, you would want to be VERY careful when evaluating code on for example a server side.

    As have been hinted to in other posts here you probably want to make a function instead of an evaluated string if you are in control of the source code that is to be run.

提交回复
热议问题