Search This Blog

Google Analytics

Tuesday, October 29, 2013

HtmlEncode and HtmlDecode In JavaScript

In web development, we often need to encode a string especially input from user so data with potential malicious intention when displayed will be safe. On server side, we can use e.g. HtmlUtility.HtmlEncode (in ASP.NET for encode) and HtmlUtility.HtmlDecode (in ASP.NET for decode).

What if we need one in JavaScript? Here's how to do just that!

<script src=""></script>

<script language="javascript" type="text/javascript">
    function htmlEncode(value) {
        return $('<div/>').text(value).html();

    function htmlDecode(value) {
        return $('<div/>').html(value).text();

    var s = "<b>hello's world</b>";
    var encoded = htmlEncode(s);
    var decoded = htmlDecode(encoded);


No comments:

Post a Comment

Do provide your constructive comment. I appreciate that.

Popular Posts