Is there any 'code/function/algoritm' to convert the javascript string?:
var alert = "alert('Hello World!')";
In javascript syntax; in this case, it would display Hello World!
on the screen.
Is there any 'code/function/algoritm' to convert the javascript string?:
var alert = "alert('Hello World!')";
In javascript syntax; in this case, it would display Hello World!
on the screen.
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:...">
.
yes, there is:
var alert = "alert('Hello World!')";
eval(alert);
Evaluates JavaScript code represented as a string.
Here is the explanation and other uses of the eval() function.
This can lead to some unanticipated problems since you are executing some arbitrary string as javascript code. If you explained why you need to do what you're doing maybe there's a safer alternative.
You can use eval
but it's highly discouraged!
var alert = "alert('This is evil');"
eval(alert);
You are looking for eval. You want to be carefull thou, this might create some security risks.
You might want to read this eval() isn’t evil, just misunderstood
var alert = "alert('Hello World!')";
eval( alert );
An better method could be something like this:
<script src="pretendToBeJavascript.php"></script>
// pretendToBeJavascript.php contents:
header('Content-type: text/javascript');
echo "alert('Hello World!')";
There is any possible solution:
var alert = "alert('Hello World!')";
eval(alert );
Make sure, that eval
is evil @Frits van Campen