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
function evaluate(expression) { const tokens = tokenize(expression); let pos = 0;
Building a recursive descent calculator
parsing
recursion
operator-precedence
Intermediate
8 steps
javascript
import { useState, useEffect, useCallback, useRef } from 'react'; const cache = new Map(); const inflight = new Map();
Building a stale-while-revalidate hook in React
caching
request-deduplication
custom-hooks
Advanced
10 steps
javascript
import { useEffect, useRef, useState } from 'react'; export function useDelayedFlag(active, delay = 300) { const [visible, setVisible] = useState(false);
Delaying a loading spinner with a React hook
custom-hooks
debouncing
cleanup
Intermediate
8 steps
javascript
const SWIPE_THRESHOLD = 80; const MAX_TRANSLATE = 120; export function attachSwipeToDismiss(element, onDismiss) {
Building a swipe-to-dismiss gesture in JS
touch-events
gesture-detection
dom-manipulation
Intermediate
10 steps
go
package httputil import ( "net"
Safely extracting the real client IP in Go
security
http
ip-spoofing
Intermediate
7 steps
javascript
const { pool } = require('./db'); function withTransaction() { return async (req, res, next) => {
A per-request transaction middleware in Express
middleware
database-transactions
connection-pooling
Advanced
7 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.