Reputation: 9555
I'm trying to find a simple easy quick way to decode and encode a text.
The best I have found is this below.
Does it make any difference using $("<div/>")
and why is it here even though there is not div?
Do you have any easier faster way to encode and decode HTML?
Code:
var myHTMLstring = "<p /> + <br /> sdfsdfdsfdsfsdfsdfsdfsfsfsfdsf";
var myEncoded = $('<div/>').text(myHTMLstring).html();
//<p /> + <br /> sdfsdfdsfdsfsdfsdfsdfsfsfsfdsf
var myDecoded = $('<div/>').html(myEncoded).text();
//<p /> + <br /> sdfsdfdsfdsfsdfsdfsdfsfsfsfdsf
Upvotes: 1
Views: 795
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;
}
Upvotes: 6