Escape HTML Special Characters

Escape ampersands, angle brackets, quotes and newlines before inserting untrusted values into HTML or attributes.

JavascriptSecurity Boundaries

Code

snippet
const HTML_ENTITIES = {
  "&": "&",
  "<": "&lt;",
  ">": "&gt;",
  '"': "&quot;",
  "'": "&#39;",
};

export function escapeHtml(value) {
  return String(value).replace(/[&<>"']/g, (character) => HTML_ENTITIES[character]);
}

export function escapeHtmlAttribute(value) {
  return escapeHtml(value).replace(/\r?\n/g, "&#10;");
}

export function escapeHtmlTemplate(strings, ...values) {
  return strings.reduce((output, chunk, index) => {
    const value = index < values.length ? escapeHtml(values[index]) : "";
    return output + chunk + value;
  }, "");
}