Encode or Decode HTML entities with jQuery

Hey folks, Just a quick tip, if you ever need to Encode or Decode a text in Javascript and happen to use the excellent jQuery library, here are the functions for it:
function htmlEncode(value){
    if (value) {
        return jQuery('<div />').text(value).html();
    } else {
        return '';
    }
}

function htmlDecode(value) {
    if (value) {
        return $('<div />').html(value).text();
    } else {
        return '';
    }
}
From the above two functions, you can Encode / Decode the "value" which was passed as a parameter.

Example - alert( htmlEncode("This is fun & stuff") );

Output: This is fun &amp; stuff

PS: JQuery is really powerful, I would highly recommend designers/ developers to use them .. Cheers !!

Share item with friends