Skip to content

Instantly share code, notes, and snippets.

@callemo
Created July 5, 2018 18:11
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save callemo/cee399e96c7e9d875e5bc643fc87a71a to your computer and use it in GitHub Desktop.
Save callemo/cee399e96c7e9d875e5bc643fc87a71a to your computer and use it in GitHub Desktop.
Escape HTML text. Distilled from `handlebars/utils.js`.
const entity = {
"&": "&",
"<": "&lt;",
">": "&gt;",
'"': "&quot;",
"'": "&#x27;",
"`": "&#x60;",
"=": "&#x3D;"
};
function escapeHTML(text) {
if (typeof text !== "string") {
if (text == null) {
return "";
} else if (!text) {
return text + "";
}
text = "" + text;
}
if (!/[&<>"'`=]/.test(text)) {
return text;
}
return text.replace(/[&<>"'`=]/g, char => entity[char]);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment