Debasish Debasish - 2 years ago 58
Javascript Question

when the alert() in string , how to convert it as a function to show the alert in javascript

when an alert() method in double quotes , then it behave like string , means when it print in console, the console screen shows the alert() . But i want, when the alert() in console.log at that time alert box will be show . i have piece of code but it does not full fill my requirement .

var msg="alert("welcome")"

when the previous code run , so the output of the console is


and no alert box will be create , if any one have idea how to create a alert box in this proccess please share with me.


Answer Source

You should use the eval() function:

The eval() function evaluates or executes an argument.

If the argument is an expression, eval() evaluates the expression. If the argument is one or more JavaScript statements, eval() executes the statements.

var msg = "alert(\"welcome\")"; // Sample message.
console.log(msg);             // Log to the console regardless.
eval(msg);                    // Evaluate the message as an expression.
// Alternatively, regarding your comment about the message being altered, you can do one of the following:
var msg = "alert('welcome')";
// Or:
var msg = 'alert("welcome")';
// Or even:
var msg = 'alert(\'welcome\')';

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download