Last active
July 28, 2021 04:50
-
-
Save mjuhl/a950fb91a235e75a8bdff22590cb1503 to your computer and use it in GitHub Desktop.
Escape HTML entities
This file contains hidden or 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
const htmlEntities = { | |
'<': '<', | |
'>': '>', | |
'"': '"', | |
"'": "'", | |
'&': "&" | |
}; | |
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 === `&><'"“‘”’test`, "Expected &><'"“‘”’test, got %s", escaped); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment