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 '<': '<',
4 '>': '>',
5 '"': '"',
6 "'": ''',
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
‹ swipe to step through ›
Walkthrough
Space play
←→ step
click any line
Three takeaways
- 1Any user-supplied string placed into innerHTML must be escaped to prevent XSS.
- 2A small character-to-entity map plus a single regex covers the five HTML-sensitive characters.
- 3Coercing input with String() guards against non-string values reaching the replacer.
Related explainers
javascript
const express = require('express'); const router = express.Router(); const { pool } = require('../db'); const redis = require('../redis');
Building a health check endpoint in Express
health-check
timeouts
promise-race
Intermediate
9 steps
go
package auth import ( "net/http"
Setting and reading secure session cookies in Go
cookies
session-management
security
Intermediate
6 steps
javascript
'use client'; import { useEffect } from 'react'; import * as Sentry from '@sentry/nextjs';
How a Next.js error boundary recovers
error-boundary
error-handling
observability
Intermediate
8 steps
typescript
type ResizeCallback = (size: { width: number; height: number }) => void; export function observeResize(callback: ResizeCallback, delay = 150) { let timeoutId: ReturnType<typeof setTimeout> | undefined;
Debouncing window resize in TypeScript
debounce
closures
event-listeners
Intermediate
6 steps
javascript
const MAX_BATCH_SIZE = 20; const FLUSH_INTERVAL = 5000; const ENDPOINT = '/api/analytics';
Batching analytics events in the browser
batching
buffering
sendbeacon
Intermediate
10 steps
javascript
export function diffIds(current, desired) { const currentSet = new Set(current); const desiredSet = new Set(desired);
Diffing sets to sync group membership
set-operations
diffing
transactions
Intermediate
8 steps
Share this explainer
Here's the card — post it anywhere.
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code
Embed this explainer
Drop the interactive walkthrough into a blog or docs. Views never cost a credit.
<iframe src="https://highlit.co/explainers/escaping-html-before-injecting-user-content-explained-javascript-3564/embed?autoplay=1" width="100%" height="520" loading="lazy" style="border:0"></iframe>
Autoplay is on by default — add ?autoplay=0 to start paused.