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, '&')
.replace(/"/g, '"')
.replace(/'/g, ''')
.replace(/</g, '<')
.replace(/>/g, '>');
}
//////////////
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, '&'],
[re_quot, '"'],
[re_apos, '''],
[re_lt, '<'],
[re_gt, '>']
];
function htmlEscape2(str) {
return String(str).replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">").replace(/\"/g, """).replace(/\"/g, "'")
}
function htmlEscape3(str) {
return String(str).replace(re_amp, '&').replace(re_quot, '"').replace(re_apos, ''').replace(re_lt, '<').replace(re_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();
}