Escape HTML Special Characters

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

JavascriptSecurity Boundaries

Code

javascriptsnippet
22 lines
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;
  }, "");
}

How it works

Escape HTML Special Characters keeps everything in the functions escapeHtml, escapeHtmlAttribute and escapeHtmlTemplate.

Putting it to use

The entry-point signature is export function escapeHtml(value)

escapeHtml is the public entry point; everything else in the file exists to support it.

Core lines

return strings.reduce((output, chunk, index) => {
  const value = index < values.length ? escapeHtml(values[index]) : "";
  return output + chunk + value;
}, "");
return String(value).replace(/[&<>"']/g, (character) => HTML_ENTITIES[character]);
return escapeHtml(value).replace(/\r?\n/g, "&#10;");

Interactive Tools for This Topic

FAQ

Are there third-party dependencies?
No. The dependency list is empty; the code stays inside the standard library. The file defines `escapeHtml`, `escapeHtmlAttribute`, `escapeHtmlTemplate` at load time.