1

I'm trying to find a simple easy quick way to decode and encode a text.

The best I have found is this below.

  1. Does it make any difference using $("<div/>") and why is it here even though there is not div?

  2. Do you have any easier faster way to encode and decode HTML?

Code:

var myHTMLstring = "<p /> + <br /> sdfsdfdsfdsfsdfsdfsdfsfsfsfdsf";

var myEncoded = $('<div/>').text(myHTMLstring).html();
//&lt;p /&gt; + &lt;br /&gt; sdfsdfdsfdsfsdfsdfsdfsfsfsfdsf


var myDecoded = $('<div/>').html(myEncoded).text();
//<p /> + <br /> sdfsdfdsfdsfsdfsdfsdfsfsfsfdsf
Hello-World
  • 9,277
  • 23
  • 88
  • 154

1 Answers1

6

It works because the jQuery text method uses createTextNode(), which replaces special characters with their HTML entity equivalents. You can fiddle with that method1 to create an alternative, but if you use jQuery anyway, the method you use is nice and swift.

1 this would be the plain javascript equivalent:

function encode(htmlstr){
   var x = document.createTextNode()
      ,y = document.createElement('div');;
   x.textContent = htmlstr;
   y.appendChild(x);
   return y.innerHTML;
}

function decode(htmlstr){
   var y = document.createElement('div');;
   y.innerHTML = htmlstr;
   return y.innerText || y.textContent;
}

or even in one go:

function htmlcode(htmlstr,doDecode){
   var x = document.createTextNode()
      ,y = document.createElement('div');;
   x.textContent = htmlstr;
   if (doDecode) { y.innerHTML = htmlstr; }
   else { y.appendChild(x); }
   return doDecode? (y.innerText || x.textContent) : y.innerHTML;
}

jsfiddle demo

KooiInc
  • 119,216
  • 31
  • 141
  • 177
  • wow great answer thanks - so i'm creating a div in memory as a placeholder type of thing but its not ever being added to the page. it could have been a

    ?
    – Hello-World Aug 12 '12 at 10:27
  • If it's never added to the DOM, `

    ` should be fine, although I would always use `

    ` to avoid browser dependent errors later on.
    – KooiInc Aug 12 '12 at 10:44
  • so then should I also rather use the div like this -- $('
    ').text(myHTMLstring).html();
    – Hello-World Aug 12 '12 at 15:08
  • 1
    Yep. Well, it's not bad anyway. I remember from the gruesome IE-days completely embty pages, e.g. when using something like `
    ` at the end of a page. On the other hand, I suppose `$('
    ')` is solved the right way by jQuery - it was *designed* to solve cross browser problems.
    – KooiInc Aug 12 '12 at 16:04