Frage

I have some code (whatever is inside the body of the jsToBeConverted function below) that I want to be able to convert it into text so that the user can copy it and then paste it inside a <script> element on their site in order to have it executed.

someElement.onclick = function ()
{
    var textForUserToCopy = (function ()
    {
      x = document.getElementById('someInput').value;

      var jsToBeConverted = function ()
      {
        var y = x + 6;

        var z = function (a)
        {
          return (a + 5);
        };

         window.d = z(y);
      };

      var jsToExecute = "(" + jsToBeConverted + ")();"

      return jsToExecute;
    })();
};

However this would generate the following text :

"(function ()
 { 
   var y = x + 6; 

   var z = function (a)
   {
     return (a + 5);
   };

   window.d = z(y);
 })();"

But this isn't what I want. If the above is evaluated x will obviously be undefined. What I want is for x to be replaced by its value at the time and then have the js converted into text. So if the value of x happened to be 123, this is what the generated text should look like :

"(function ()
 {
   var y = 6 + 6; 

   var z = function (a)
   {
     return (a + 5);
   };

   window.d = z(y);
 })();"

If the above string is evaluated - window.d would be 17

Is the there some standard function/process for generating/converting dynamic code into text?

Thank you

War es hilfreich?

Lösung

You can simply concatenate.

e.g.:

"function (x) { return " + generated_value + " + x }";

For a more elegant looking solution, see string formatting: JavaScript equivalent to printf/string.format

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top