Hello-World
Hello-World

Reputation: 9555

why does this work to encode and decode HTML

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

Upvotes: 1

Views: 795

Answers (1)

KooiInc
KooiInc

Reputation: 122916

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

Upvotes: 6

Related Questions