Quick and Dirty HtmlEncode/Decode Javascripts

by Jason Haley 13. September 2006 14:56

I think I wrote these scripts about 3 or 4 years ago, but this week I found myself digging through the archives looking for them.  I say they are quick and dirty because they only handle the standard escape codes, hopefully this will save someone else some time.

// Replace the &, >, <, " characters
function HtmlEncode(text)
{
    var result = text; 

    var amp = /&/gi;
    var gt = />/gi;
    var lt = /</gi;
    var quot = /"/gi;
    var apos = /'/gi;
 

    var html_gt = "&gt;";
    var html_lt = "&lt;";
    var html_amp = "&amp;";
    var html_quot = "&quot;";
    var html_apos = "&apos;";

    result = result.replace(amp, html_amp);
    result = result.replace(quot, html_quot);
    result = result.replace(lt, html_lt);
    result = result.replace(gt, html_gt);
    result = result.replace(apos, html_apos);

    return result;
}

// Replace the &amp;, &gt;, &lt;, &quot;, &apos; entities
function HtmlDecode(text)
{
    var result = text;

    var amp = "&";
    var gt = ">";
    var lt = "<";
    var quot = "\"";
    var apos = "'";
 

    var html_gt = /&gt;/gi;
    var html_lt = /&lt;/gi;
    var html_amp = /&amp;/gi;
    var html_quot = /&quot;/gi;
    var html_apos = /&apos;/gi;

    result = result.replace(html_amp, amp);
    result = result.replace(html_quot, quot);
    result = result.replace(html_lt, lt);
    result = result.replace(html_gt, gt);
    result = result.replace(html_apos, apos);

    return result;
}

Comments (0) | Post RSSRSS comment feed |

Categories:
Tags:

Comments are closed