Skip to content

Instantly share code, notes, and snippets.

@madrobby
Created May 9, 2011 03:13
Show Gist options
  • Star 7 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save madrobby/961994 to your computer and use it in GitHub Desktop.
Save madrobby/961994 to your computer and use it in GitHub Desktop.
function escapeHTML(s,r){r='replace';return s[r](/&/g,'&amp;')[r](/>/g,'&gt;')[r](/</g,'&lt;')}
@jed
Copy link

jed commented May 9, 2011

escapeHTML=function(s){with(document)return createElement("b").appendChild(createTextNode(s)).parentNode.innerHTML}

@jed
Copy link

jed commented May 9, 2011

better yet:

escapeHTML=function(d,b,t){b=d.createElement("b");t=b.appendChild(d.createTextNode());return function(s){t.nodeValue=s;return b.innerHTML}}(document)

@madrobby
Copy link
Author

madrobby commented May 9, 2011

Via @4esn0k on Twitter:

function escapeHTML(s){return s.replace(/[&<>]/g,function (p){return '&#'+p.charCodeAt(0)+';'})}

@jed
Copy link

jed commented May 9, 2011

definitely the way to go if we can assume the browser only escapes those... is it true?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment