Escaping for text and attributes
Escape HTML when you must build it
Lesson 5 of 20 · 10 min · Module 2: Safe HTML and pages
Sometimes building an HTML string is the practical choice: an email template, a page rendered on the server, or a large table. Then every value must be escaped, so its characters are shown instead of being read as markup.
Start this lesson →Free. No installation: you write and run the code in your browser, and it is checked automatically.
By the end, you’ll be able to…
- Escape the five special HTML characters
- Know where escaped text is safe and where it is not
- Prefer DOM methods when you can
The idea
Escaping replaces the five characters with a meaning in HTML by entities: & becomes &, < becomes <, > becomes >, " becomes " and ' becomes '. Replace & first, or you will escape your own entities a second time. Escaped text is safe between tags and inside quoted attributes, but not inside <script>, event attributes or addresses.
const name = '<b>Ana</b> & co';
const safe = name.replaceAll('&', '&').replaceAll('<', '<').replaceAll('>', '>');
console.log(safe); // <b>Ana</b> & co
01Entities show characters instead of markup
< is drawn as < but can never start a tag. Escaping turns any text into characters and entities that look exactly the same on screen.
console.log(escapeHTML('<b>Hi</b>'));<b>Hi</b>02Order matters
Replace & before everything else. Done last, it would turn the < you just produced into &lt;, and the page would show the entity text instead of <.
03Escaping depends on the context
Escaped text is safe between tags and inside quoted attribute values. Inside <script>, style, event attributes such as onclick, or addresses, it is not enough: there, use DOM methods, JSON for data, and the address checks from earlier lessons.
Your turn
escapeHTML(value). It turns any value into text with String() and replaces &, <, >, " and ' with &, <, >, " and '. The table code already uses it for every value, including the title attribute.What the checks look for
- The five special characters are escaped
- & is escaped exactly once
- Other values become text
- The table shows every order
- Markup in orders stays plain text
- Attribute values cannot break out
Take this with you
When you must build HTML, escape every value, & first, and quote every attribute.
Go a little further
Write a tagged template html`…` that escapes every value placed in it automatically.