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 !!



Comments
2 Responses to “Encode or Decode HTML entities with jQuery”
  1. Paketresor says:

    hello! ;) im at work currently, hence i do not have much time to write… but! I really appreciated reading through this article. It was a bunch of great stuff. thank you! Sincerely, Miss Paketresor

  • My Experience

    My expertise are primarily in C#, ASP.NET, HTML, JavaScript, SQL, SEO, Windows Services, XML and Web services. Areas of technical expertise are in Web application design and architecture and security.
  • Quote of the Day !!

    "Be nice to nerds. Chances are you'll end up working for one." – Bill Gates