Skip to content
Justice Tech School

Rendering HTML

Servers often build HTML from data. Escape every value you insert, otherwise users can inject scripts.

Example
const esc = (s) => String(s).replace(/[&<>"']/g, (c) => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' }[c]));
const render = (items) => `<ul>${items.map((i) => `<li>${esc(i)}</li>`).join('')}</ul>`;
console.log(render(['A & B', '<script>alert(1)</script>']));

Result

<ul><li>A &amp; B</li><li>&lt;script&gt;alert(1)&lt;/script&gt;</li></ul>

Exercise

Name the attack.

 injection

Quiz Test

Why escape HTML?

These free lessons are for learning. Join a full course for projects, mentor feedback and a verified certificate.