Escape HTML Special Characters
Escape ampersands, angle brackets, quotes and newlines before inserting untrusted values into HTML or attributes.
Code
const HTML_ENTITIES = {
"&": "&",
"<": "<",
">": ">",
'"': """,
"'": "'",
};
export function escapeHtml(value) {
return String(value).replace(/[&<>"']/g, (character) => HTML_ENTITIES[character]);
}
export function escapeHtmlAttribute(value) {
return escapeHtml(value).replace(/\r?\n/g, " ");
}
export function escapeHtmlTemplate(strings, ...values) {
return strings.reduce((output, chunk, index) => {
const value = index < values.length ? escapeHtml(values[index]) : "";
return output + chunk + value;
}, "");
}Report a problem with this exampleOpens a pre-filled issue on GitHub.