/    Sign up×
Community /Pin to ProfileBookmark

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!

to post a comment
JavaScript

4 Comments(s)

Copy linkTweet thisAlerts:
@xelawhoDec 30.2011 — 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>")
[/CODE]


but Opera doesn't like it :mad:

maybe a regex expert can help you out.
Copy linkTweet thisAlerts:
@jalarieDec 30.2011 — 
[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>")
[/CODE]
[/QUOTE]

You missed the semicolon (? at the end of the "lt" item:
<i>
</i>func=f.toString().replace("&lt;","&amp;lt;");
Copy linkTweet thisAlerts:
@xelawhoDec 30.2011 — 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...
Copy linkTweet thisAlerts:
@ypsdauthorDec 31.2011 — 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...[/QUOTE]

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.
×

Success!

Help @ypsd spread the word by sharing this article on Twitter...

Tweet This
Sign in
Forgot password?
Sign in with TwitchSign in with GithubCreate Account
about: ({
version: 0.1.9 BETA 5.17,
whats_new: community page,
up_next: more Davinci•003 tasks,
coming_soon: events calendar,
social: @webDeveloperHQ
});

legal: ({
terms: of use,
privacy: policy
});
changelog: (
version: 0.1.9,
notes: added community page

version: 0.1.8,
notes: added Davinci•003

version: 0.1.7,
notes: upvote answers to bounties

version: 0.1.6,
notes: article editor refresh
)...
recent_tips: (
tipper: @AriseFacilitySolutions09,
tipped: article
amount: 1000 SATS,

tipper: @Yussuf4331,
tipped: article
amount: 1000 SATS,

tipper: @darkwebsites540,
tipped: article
amount: 10 SATS,
)...