Skip to content

Instantly share code, notes, and snippets.

@mjuhl
Last active July 28, 2021 04:50
Show Gist options
  • Save mjuhl/a950fb91a235e75a8bdff22590cb1503 to your computer and use it in GitHub Desktop.
Save mjuhl/a950fb91a235e75a8bdff22590cb1503 to your computer and use it in GitHub Desktop.
Escape HTML entities
const htmlEntities = {
'<': '&lt;',
'>': '&gt;',
'"': '&quot;',
"'": "&#39;",
'&': "&amp;"
};
const htmlCharExpr = new RegExp(`[${Object.keys(htmlEntities).join('')}]`, 'g');
function escapeHtml (string) {
return string.replace(htmlCharExpr, char => htmlEntities[char]);
}
function escapeHtmlTest () {
const string = `&><'"“‘”’test`;
const escaped = escapeHtml(string);
console.log("Escaped: %s", escaped);
console.assert(escaped === `&amp;&gt;&lt;&#39;&quot;“‘”’test`, "Expected &amp;&gt;&lt;&#39;&quot“‘”’test, got %s", escaped);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment