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
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
You can use :
f.toString();
function f(a, b, c) {
}
document.write(f.toString().replace(/\n/g, "<br>"));
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);
}"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With