11

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

3 Answers 3

8

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

Sign up to request clarification or add additional context in comments.

Comments

4

You can use :

 f.toString();

function f(a, b, c) {

}

document.write(f.toString().replace(/\n/g, "<br>"));

Comments

1

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);
 }"

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.