Encode/Decode HTML

by QMaster

HTML

Write HTML in first box and change focus
<br/>

<input id="txt1"/>
<br/>
<input id="txt2" />
<div id="cnt1"></div>
<br/>
<input id="txt3" />
<br/>
<input id="txt4" />
<br/>
<input id="txt5" />
<div id="cnt2"></div>

CSS

input
{
    width: 400px;    
}

JavaScript

$('#txt1').change(function(){ 
    $('#txt2').val(htmlEncode($(this).val()));   
    $('#txt3').val(htmlDecode($('#txt2').val()));   
    $('#cnt1').html(htmlDecode($('#txt2').val()));   
    
    $('#txt4').val(htmlEscape3($(this).val()));
    $('#txt5').val(htmlDecode($('#txt4').val())); 
    $('#cnt2').html(htmlDecode($('#txt4').val()));
});
                                 
    

//$("#single").val("Single2").change();

function htmlEscape(str) {
    return String(str)
            .replace(/&/g, '&amp;')
            .replace(/"/g, '&quot;')
            .replace(/'/g, '&#39;')
            .replace(/</g, '&lt;')
            .replace(/>/g, '&gt;');
}

//////////////
var re_all = /[&"'\<\>]/g;
    var re_amp = /&/g;
    var re_quot = /"/g;
    var re_apos = /'/g;
    var re_lt = /</g;
    var re_gt = />/g;

var re_arr = [
      [re_amp, '&amp;'],
      [re_quot, '&quot;'],
      [re_apos, '&#39;'],
      [re_lt, '&lt;'],
      [re_gt, '&gt;']
    ];

function htmlEscape2(str) {
return String(str).replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/\"/g, "&quot;").replace(/\"/g, "&#039;")
}

function htmlEscape3(str) {
return String(str).replace(re_amp, '&amp;').replace(re_quot, '&quot;').replace(re_apos, '&#39;').replace(re_lt, '&lt;').replace(re_gt, '&gt;');
}

//////////////


function htmlEncode(value){
  //create a in-memory div, set it's inner text(which jQuery automatically encodes)
  //then grab the encoded contents back out.  The div never exists on the page.
  return $('<div/>').text(value).html();
}

function htmlDecode(value){
  return $('<div/>').html(value).text();
}