Search code examples
javascript

Execute JavaScript code stored as a string


How do I execute some JavaScript that is a string?

function ExecuteJavascriptString()
{
    var s = "alert('hello')";
    // how do I get a browser to alert('hello')?
}

Solution

  • With the eval function, like:

    eval("my script here");
    

    But please heed the warning message from the MDN page:

    Warning: Executing JavaScript from a string is an enormous security risk. It is far too easy for a bad actor to run arbitrary code when you use eval(). [...]