Web design
Escape text for HTML display
Show literal user content without interpreting it as markup.
1. Identify context
HTML text, attributes, CSS and JavaScript need different escaping. Choose the context before transforming data.
2. Escape text
Encode ampersands and angle brackets for HTML source, or assign DOM textContent when possible.
3. Inspect output
A sample containing <b> and ampersands should display literally, not become active HTML.
4. Know the limit
Text escaping is not full HTML sanitization or URL validation. Use context-appropriate methods.
Display a literal HTML fragment
Enter the literal text <b>A & B</b> into HTML text escaping. In an HTML text context the escaped source should contain encoded angle brackets and ampersand; the rendered page should show the original fragment as text rather than bold markup. Where possible insert untrusted text through DOM textContent.
Common pitfall
HTML text escaping does not validate URLs, sanitize arbitrary markup or make a string safe in JavaScript or CSS. Use a context-specific API; don't concatenate the escaped output into an unrelated executable context.