0

For example, if i have something like this:

function hello() {console.log("hello")}

I want to be able to make a function in java script that would return a string value:

"console.log("hello");"    

Is there a way to do this with plain javascript?

musefan
  • 47,875
  • 21
  • 135
  • 185
Pixeladed
  • 1,773
  • 5
  • 14
  • 26
  • 1
    What would you need that for? – Bergi Sep 24 '13 at 15:49
  • 1
    Sometimes `toString` is overridden, which is why it's better to use `Function.prototype.toString.call(hello);`. However, there is almost no use-case where this is a good solution and very likely there is a much better solution to your actual problem if you let us know more about it. – Ingo Bürk Sep 24 '13 at 16:02

3 Answers3

1

If you do hello.toString() it will output "function hello() {console.log("hello")}"

Zach Lysobey
  • 14,959
  • 20
  • 95
  • 149
  • but see [the question yours duplicates](http://stackoverflow.com/questions/14885995/how-to-get-a-functionss-body-as-string) for the complete answer – Zach Lysobey Sep 24 '13 at 15:38
1

You can get all of the code including the function declaration by calling the toString() method on the function. You can then parse this string to remove the unwanted information.

Something like this:

function hello() {
    console.log("hello");
}

var f = hello.toString();//get string of whole function
f = f.substring(f.indexOf('{') + 1);//remove declaration and opening bracket
f = f.substring(0, f.length - 1);//remove closing bracket
f = f.trim();//remove extra starting/eding whitespace

console.log(f);

Here is a working example

musefan
  • 47,875
  • 21
  • 135
  • 185
0

The others has already provided the right answer if you base directly from the function created, but if you want to create a literal string instead. Just quote it properly:

function hello() { return "console.log(\"hello\")"; };

This should show console.log("hello") on the page anyhow.

<html><head></head><body><script>
    function hello() { return "console.log(\"hello\")"; };
    document.write(hello());
</script><body></html>
konsolebox
  • 72,135
  • 12
  • 99
  • 105