HTML Encode in Javascript

$(document).ready(function(){
	var str = '<script>alert("hey");<\/script>';
	$('#test').html(htmlEncode(str));
});

function htmlEncode ( str ) {
	var ele = document.createElement('span');
	ele.appendChild( document.createTextNode( str ) );
	return ele.innerHTML;
}
 
function htmlDecode ( str ) {
	var ele = document.createElement('span');
	ele.innerHTML = str;
	return ele.textContent || ele.innerText;
}

Reference:

  1. http://www.lenashane.com/article/20151104-1035.html
  2. http://cwe.mitre.org/data/definitions/79.html