javascript 27 lines · 6 steps

Escaping HTML before injecting user content

A lookup table and a regex turn untrusted strings into safe HTML before they hit innerHTML.

Explained by highlit
1const ESCAPE_MAP = {
2 '&': '&',
3 '<': '&lt;',
4 '>': '&gt;',
5 '"': '&quot;',
6 "'": '&#39;',
7};
8 
9function escapeHtml(value) {
10 return String(value).replace(/[&<>"']/g, (char) => ESCAPE_MAP[char]);
11}
12 
13function renderComment(container, comment) {
14 const article = document.createElement('article');
15 article.className = 'comment';
16 article.dataset.commentId = comment.id;
17 
18 article.innerHTML = `
19 <header class="comment__header">
20 <span class="comment__author">${escapeHtml(comment.author)}</span>
21 <time datetime="${escapeHtml(comment.createdAt)}">${escapeHtml(comment.createdAtLabel)}</time>
22 </header>
23 <p class="comment__body">${escapeHtml(comment.body)}</p>
24 `;
25 
26 container.appendChild(article);
27}
01 / 01
STEP 01

Walkthrough

Space play step click any line
Three takeaways
  1. 1Any user-supplied string placed into innerHTML must be escaped to prevent XSS.
  2. 2A small character-to-entity map plus a single regex covers the five HTML-sensitive characters.
  3. 3Coercing input with String() guards against non-string values reaching the replacer.

Related explainers

Share this explainer

Here's the card — post it anywhere.

Escaping HTML before injecting user content — share card
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code