Escape HTML Entities for Output
Escape untrusted text before inserting it into HTML so angle brackets and quotes cannot break out of the surrounding context.
Code
const ENTITIES = {
"&": "&",
"<": "<",
">": ">",
'"': """,
"'": "'",
};
export function escapeHtml(text) {
if (text === null || text === undefined) return "";
return String(text).replace(/[&<>"']/g, (char) => ENTITIES[char]);
}Inside the snippet
Count the function escapeHtml as the entire surface area of Escape HTML Entities for Output.
Watch out for
- The guard
text === null || text === undefinedshort-circuits the flow with an earlyreturnwhen its condition holds.
Putting it to use
Entry signature: export function escapeHtml(text)
Treat escapeHtml as the API: import it, and ignore the supporting code.
Core lines
return String(text).replace(/[&<>"']/g, (char) => ENTITIES[char]);
if (text === null || text === undefined) return "";
Interactive Tools for This Topic
CSP Header BuilderBuild a Content-Security-Policy header from per-directive sources, skipping empty ones and rejecting a blanket wildcard.HTML Entity Encoder / DecoderEncode the five HTML-significant characters and decode named or numeric entities, with optional numeric encoding for non-ASCII text.Regex Escape GeneratorEscape plain text so it can be embedded safely in a JavaScript RegExp, covering all metacharacters like dots, brackets, braces, and backslashes.Multi-Mode Escape & Unescape CodecEscape and unescape strings safely across JSON, JavaScript, SQL single-quoted literals, POSIX shell single quotes, and RFC 4180 CSV cells in your browser.
FAQ
- Can I paste this into a project as-is?
- Yes. Paste it in and run; no package manager step is needed. The file defines `escapeHtml` at load time.
Report a problem with this exampleOpens a pre-filled issue on GitHub.