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 &amp;, < becomes &lt;, > becomes &gt;, " becomes &quot; and ' becomes &#39;. 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('&', '&amp;').replaceAll('<', '&lt;').replaceAll('>', '&gt;');
console.log(safe); // &lt;b&gt;Ana&lt;/b&gt; &amp; co

01Entities show characters instead of markup

&lt; 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>'));
Output
&lt;b&gt;Hi&lt;/b&gt;

02Order matters

Replace & before everything else. Done last, it would turn the &lt; you just produced into &amp;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

Write escapeHTML(value). It turns any value into text with String() and replaces &, <, >, " and ' with &amp;, &lt;, &gt;, &quot; and &#39;. 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
Try it in the editor →

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.

Learn Web Security Foundations for free

20 short lessons with real code and instant checks.

See the whole course →