JS print function code

I want to get all the function code (with parameters) and print it in div.code

html file

<script src='script.js'></script> ... <input type=text value='text' id='my_input'> <div class='code'></div> <script> document.querySelectorAll('div.code')[0].innerHTML=func(document.getElementById('my_input')); </script> 

script.js

 function func(param){ console.log(param); } 

So in div.code this should be

 "function func(text){ console.log(text) }" 

What should I use for this? I tried using toString, toSource, JSON.stringify, but it does not work.

+8
javascript function
source share
3 answers

You must use String() to create a string from function code

 function f(param) { console.log(param); } alert( String(f) ); // ...innerHTML = String(f); 

If you want to replace param with your input, you can work with the result of String(f) as a string

 alert( String(f).replace(/param/g, 'text') ); // ...innerHTML = String(f).replace(/param/g, document.getElementById('my_input')); 

Take a look at this jsFiddle example


Also read here more about String () Function

+6
source share

You can use:

  f.toString(); 

 function f(a, b, c) { } document.write(f.toString().replace(/\n/g, "<br>")); 
+3
source share

I would recommend calling the vanilla toString function of the Function object to strengthen your function as follows:

 Function.prototype.toString.call(yourFunctionHere); //or just use it directly on your function, if you're not going to modify the prototype yourFunction.toString(); 

This prints your function as you mentioned.

If you want to replace values ​​later, you can use replace in combination with the regular expression.

Like this:

 function myFunction(param1){ alert(param1); } Function.prototype.toString.call(myFunction).replace(new RegExp('param1', 'g'), 'theParam'); 

This will give you the following:

 "function myFunction(theParam){ alert(theParam); }" 
+1
source share

All Articles