Skip to content

Instantly share code, notes, and snippets.

@receptor
Created January 27, 2017 16:30
Show Gist options
  • Save receptor/01a7bac6ab72455f51a18cd021ae6482 to your computer and use it in GitHub Desktop.
Save receptor/01a7bac6ab72455f51a18cd021ae6482 to your computer and use it in GitHub Desktop.
Cross-browser safe and fast HTML sanitizer
// 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