Fog Creek Software
Discussion Board

Welcome! and rules

Joel on Software

Javascript Encoding HTML Friendly

Hey all, sorry for the deluge of posts.

I'm writing a simple program in Javascript that dynamically processes Xpaths. So when I read a xml document, I want to display it in a Div with the innerHTML property. To take care the the > and <, I do a string replace. But I was wondering if there is a built in function for doing this type of encoding rather than a search/replace.

I had posted earlier about problems with certain Xpaths - while they may have been real the big problem is my encoding. I am doing search/replace but because of my lack of skill with regular expressions, these may be malfunctioning.  I'm thinking there might be something in javsacript similar to a Server.HtmlEncode in ASP.NET.

Anyone know?

David Seruyange
Thursday, December 16, 2004


Thursday, December 16, 2004

someElement.innerText = textWithTags;

...but bear in mind that innerText is IE-only (the last time I checked). Otherwise no, javascript doesn't have an HTML encode function built-in (there's and escape() function but that does URL-encoding).

Duncan Smart
Tuesday, December 21, 2004

try this:
function htmlEncode(s) {
        var str = new String(s);
        str = str.replace(/&/g, "&amp;");
        str = str.replace(/</g, "&lt;");
        str = str.replace(/>/g, "&gt;");
        str = str.replace(/"/g, "&quot;");
        return str;

Wednesday, January 26, 2005

*  Recent Topics

*  Fog Creek Home