-2

是否有任何“代码/函数/算法”来转换 javascript 字符串?:

var alert = "alert('Hello World!')";

在javascript语法中;在这种情况下,它将显示Hello World!在屏幕上。

4

5 回答 5

2

You may consider creating a parser specific to your use case. This will limit the power of eval to exclusively your intended behavior, for example, the following limits the code to execution of a global function.

var parse_vals = function(expr) {
    if( expr.match(/^['"][^'"]+['"]$/) ) {
        // parse a string literal
        return expr.substr(1, expr.length - 2);
    } else if( !isNaN(parseInt(expr)) ) {
        // parse a number
        return parseInt(expr);
    } else {
        // fail in parsing literal
        return null;
    }
};
var alert_str = "alert('Hello World!')",
    comps = alert_str.match(/^([^(]+)\(([^)]+)\)$/);
    // => ["alert(...)", "alert", "'Hello World!'"]
if( comps ) {
    // apply a global function to the provided arguments, parsed.
    // all values thus need to be literals, no variable access.
    window[comps[1]].apply(window, comps[2].split(/,\s?/).map(parse_vals));
} else {
    alert("Invalid code provided.");
}

As others have stated, eval is unsafe and should be used with caution if used at all. Hence, a use-case-specific parser is a much better solution. More importantly, the power of a full-blown child evaluator is going to be overkill, no matter what. The components of the expression which will vary can be singled out and handled. If the entire string is variable, you are allowing an arbitrary program to be run, and so might as well include it as an independent script, e.g., <script src="data:...">.

于 2013-08-05T15:22:35.897 回答
0

就在这里:

var alert = "alert('Hello World!')";

eval(alert);

评估表示为字符串的 JavaScript 代码。

这是 eval() 函数的解释和其他用途。

这可能会导致一些意想不到的问题,因为您正在执行一些任意字符串作为 javascript 代码。如果你解释了为什么你需要做你正在做的事情,也许有一个更安全的选择。

于 2013-08-05T15:16:57.490 回答
0

您可以使用eval,但非常不鼓励!

var alert = "alert('This is evil');"
eval(alert);
于 2013-08-05T15:17:05.430 回答
0

您正在寻找评估。你要小心,这可能会产生一些安全风险。

您可能想阅读此eval() 不是邪恶的,只是被误解了

var alert = "alert('Hello World!')"; 
eval( alert );

更好的方法可能是这样的:

<script src="pretendToBeJavascript.php"></script>

// pretendToBeJavascript.php contents:
header('Content-type: text/javascript');
echo "alert('Hello World!')";
于 2013-08-05T15:17:25.743 回答
-1

There is any possible solution:

var alert = "alert('Hello World!')";
eval(alert );

Make sure, that eval is evil @Frits van Campen

When is JavaScript's eval() not evil?

于 2013-08-05T15:19:40.957 回答