Created
December 7, 2012 17:56
-
-
Save mindscratch/4235080 to your computer and use it in GitHub Desktop.
un/escape HTML in Javascript
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 the browser's built-in functionality to quickly and safely escape the | |
// string | |
function escapeHtml(str) { | |
var div = document.createElement('div'); | |
div.appendChild(document.createTextNode(str)); | |
return div.innerHTML; | |
}; | |
// UNSAFE with unsafe strings; only use on previously-escaped ones! | |
function unescapeHtml(escapedStr) { | |
var div = document.createElement('div'); | |
div.innerHTML = escapedStr; | |
var child = div.childNodes[0]; | |
return child ? child.nodeValue : ''; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment