www.webdeveloper.com
Results 1 to 5 of 5

Thread: how to print function body (must be readable) in html?

  1. #1
    Join Date
    Jul 2010
    Posts
    11

    how to print function body (must be readable) in html?

    f=function(x,y){if(x<y){return x*3;}else{return y*2}}
    document.write("<p>" + f.toString() + "</p>")

    I guess my question is naive. But I ask anyway, as I don't find a good webpage for answering it.

    Suppose I run the above code in the browser, I will get the following in the html. Does anybody know how to print an option/function in html? The result must be human readable (meaning with proper indentation).

    "function (x,y){if(x"

    Thanks!

  2. #2
    Join Date
    Nov 2010
    Posts
    1,058
    IE doesn't like the < symbol. Firefox doesn't mind.

    they are both OK with this:
    Code:
    f=function(x,y){if(x<y){return x*3;}else{return y*2}}
    func=f.toString().replace("<","&lt");
    document.write("<p>" + func + "</p>")
    but Opera doesn't like it

    maybe a regex expert can help you out.

  3. #3
    Join Date
    Nov 2002
    Location
    Flint, Michigan, USA
    Posts
    588
    Quote Originally Posted by xelawho View Post
    Code:
    f=function(x,y){if(x<y){return x*3;}else{return y*2}}
    func=f.toString().replace("<","&lt");
    document.write("<p>" + func + "</p>")
    You missed the semicolon (;) at the end of the "lt" item:
    Code:
    func=f.toString().replace("<","&lt;");

  4. #4
    Join Date
    Nov 2010
    Posts
    1,058
    good eyes, jalarie. Now it works on IE, FF, Chrome and Opera. I can't help but think there must be some more efficient, regexy way of doing this, rather than replacing string characters on a case by case basis, though...

  5. #5
    Join Date
    Jul 2010
    Posts
    11
    Quote Originally Posted by xelawho View Post
    good eyes, jalarie. Now it works on IE, FF, Chrome and Opera. I can't help but think there must be some more efficient, regexy way of doing this, rather than replacing string characters on a case by case basis, though...
    Yes. I would like a more general API (probably just one simple function call to hide all the details) that can do the conversion correctly for all cases so that I don't have to worry what special characters to replace.

Thread Information

Users Browsing this Thread

There are currently 1 users browsing this thread. (0 members and 1 guests)

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  
HTML5 Development Center



Recent Articles