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
It works because the jQuery
textmethod usescreateTextNode(), 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:
or even in one go:
jsfiddle demo