Skip to content

Instantly share code, notes, and snippets.

@thomasJang
Created October 29, 2016 13:23
Show Gist options
  • Save thomasJang/aec059a50ffd7a6bf4e262fae42a664c to your computer and use it in GitHub Desktop.
Save thomasJang/aec059a50ffd7a6bf4e262fae42a664c to your computer and use it in GitHub Desktop.
htmlEncode
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 ) ) );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment