Skip to content

Instantly share code, notes, and snippets.

@mindscratch
Created December 7, 2012 17:56
Show Gist options
  • Save mindscratch/4235080 to your computer and use it in GitHub Desktop.
Save mindscratch/4235080 to your computer and use it in GitHub Desktop.
un/escape HTML in Javascript
// 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