Created
August 30, 2013 04:19
-
-
Save bennyzhao/6386280 to your computer and use it in GitHub Desktop.
HTML encoding
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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> & hello</div>'; | |
document.getElementById( 'same' ).textContent = | |
'html === htmlDecode( htmlEncode( html ) ): ' | |
+ ( html === htmlDecode( htmlEncode( html ) ) ); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!-- for hue --> | |
<input id="hidden" type="hidden" value="chalk & 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