Skip to content

Instantly share code, notes, and snippets.

@thetallweeks
Created November 5, 2014 17:14
Show Gist options
  • Save thetallweeks/7c452e211f286e77b6f2 to your computer and use it in GitHub Desktop.
Save thetallweeks/7c452e211f286e77b6f2 to your computer and use it in GitHub Desktop.
Little function for escaping html characters (in TypeScript)
// From Tom Gruner @ http://stackoverflow.com/a/12034334/1660815
var entityMap = {
"&": "&",
"<": "&lt;",
">": "&gt;",
'"': '&quot;',
"'": '&#39;',
"/": '&#x2F;'
};
function escapeHtml(source: string) {
return String(source).replace(/[&<>"'\/]/g, s => entityMap[s]);
}
@lele-blue
Copy link

A null-check-resistant variant:

const entityMap = new Map<string, string>(Object.entries({
    "&": "&amp;",
    "<": "&lt;",
    ">": "&gt;",
    '"': '&quot;',
    "'": '&#39;',
    "/": '&#x2F;'
}))

export function escape_html(source: string) {
    return String(source).replace(/[&<>"'\/]/g, (s: string) => entityMap.get(s)!);
}

@magast
Copy link

magast commented Jan 3, 2022

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