Execute JavaScript code stored as a string

前端 未结 20 1051
北荒
北荒 2020-11-22 08:58

How do I execute some JavaScript that is a string?

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


        
20条回答
  •  不要未来只要你来
    2020-11-22 09:25

    Not sure if this is cheating or not:

    window.say = function(a) { alert(a); };
    
    var a = "say('hello')";
    
    var p = /^([^(]*)\('([^']*)'\).*$/;                 // ["say('hello')","say","hello"]
    
    var fn = window[p.exec(a)[1]];                      // get function reference by name
    
    if( typeof(fn) === "function") 
        fn.apply(null, [p.exec(a)[2]]);                 // call it with params
    

提交回复
热议问题