Skip to content

Instantly share code, notes, and snippets.

@bennyzhao
Created August 30, 2013 04:19
Show Gist options
  • Save bennyzhao/6386280 to your computer and use it in GitHub Desktop.
Save bennyzhao/6386280 to your computer and use it in GitHub Desktop.
HTML encoding
// use jQuery
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();
}
// hue javascript
function htmlEncode( html ) {
return document.createElement( 'a' ).appendChild(
document.createTextNode( html ) ).parentNode.innerHTML;
};
function htmlDecode( html ) {
var a = document.createElement( 'a' ); a.innerHTML = html;
return a.textContent;
};
document.getElementById( 'text' ).value = htmlEncode( document.getElementById( 'hidden' ).value );
//sanity check
var html = '<div> &amp; hello</div>';
document.getElementById( 'same' ).textContent =
'html === htmlDecode( htmlEncode( html ) ): '
+ ( html === htmlDecode( htmlEncode( html ) ) );
<!-- for hue -->
<input id="hidden" type="hidden" value="chalk &amp; cheese" />
<input id="text" value="" />
<div id="same"></div>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment