Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Print function code with parameters JS

I want to get all 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 it should be

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

What should I use to do it ? I tried to use toString, toSource, JSON.stringify but it does not work

like image 661
Oloji Avatar asked Dec 15 '16 09:12

Oloji


3 Answers

You should use String() to create 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 operate on String(f) result as on 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

like image 65
m.antkowicz Avatar answered Oct 13 '22 10:10

m.antkowicz


You can use :

 f.toString();

function f(a, b, c) {

}

document.write(f.toString().replace(/\n/g, "<br>"));
like image 35
Sky Voyager Avatar answered Oct 13 '22 10:10

Sky Voyager


I would recommend calling the vanilla toString function of the Function Object to stringify your function like this:

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 like you mentioned.

If you want to replace values afterwards, you can use replace in combination with regex.

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);
 }"
like image 36
Joschua Schneider Avatar answered Oct 13 '22 08:10

Joschua Schneider