Displaying HTML through JavaScript

JavaScript and client side scripting.

Moderator: General Moderators

Post Reply
GeXus
Forum Regular
Posts: 631
Joined: Sat Mar 11, 2006 8:59 am

Displaying HTML through JavaScript

Post by GeXus »

I'm wondering what the best way is to ensure that HTML is properly encoded to work with document.write... Basically I have a template editor that can manage multiple html templates, I will parse through this and use javascript to write it out onto the page...

What's the best way to escape HTML to work with document.write? This includes handling single, double quotes, slashes, etc...
User avatar
feyd
Neighborhood Spidermoddy
Posts: 31559
Joined: Mon Mar 29, 2004 3:24 pm
Location: Bothell, Washington, USA

Post by feyd »

Unless you're calling the method directly with a string, there's nothing it generally cares about. The basics can be handled with addcslashes().
GeXus
Forum Regular
Posts: 631
Joined: Sat Mar 11, 2006 8:59 am

Post by GeXus »

feyd wrote:Unless you're calling the method directly with a string, there's nothing it generally cares about. The basics can be handled with addcslashes().
Now that i'm playing around, it looks like the only thing I have to add a backslash to are single quotes, if i have the document.write wrap everything in double quotes... does that sound right?

Would addslashes be more effective than just str_replace()?
User avatar
feyd
Neighborhood Spidermoddy
Posts: 31559
Joined: Mon Mar 29, 2004 3:24 pm
Location: Bothell, Washington, USA

Post by feyd »

You also need to swap carriage returns for \n because Javascript doesn't magically support line spanning for strings the way we're accustomed to them.

You don't need to escape opposing quotes, only similar ones. i.e. double quotes in single quote strings and single quotes in double quote strings do not need escaping. Only doubles in doubles and singles in singles.
Post Reply