HTML Text Node (textContent)
Safest way to inject user text into the DOM without interpreting as HTML.
Demo
demo.textContent = userInput;
Type any text (even tricky characters or HTML), then click “Transform”. This shows multiple safe representations and where each is appropriate.
textContent)Safest way to inject user text into the DOM without interpreting as HTML.
demo.textContent = userInput;
escapeAttribute)Encodes characters problematic in attributes (quotes, ampersands, <,>).
el.setAttribute("title", escapeAttribute(userInput));
JSON.stringify)Produces a valid JSON string literal containing your text.
const payload = { comment: userInput };
const json = JSON.stringify(payload);
encodeURIComponent)Percent-encodes a component for safe inclusion in URLs.
const u = new URL("https://example.test/");
u.searchParams.set("q", userInput);
u.toString();
Escapes characters with special meaning in regular expressions.
const re = new RegExp(escapeForRegex(userInput), "g");
Double-quotes field and doubles inner quotes per RFC4180 practice.
// Emit a row with a single field:
const row = toCSVField(userInput);
Encodes arbitrary text (including Unicode) to Base64 via UTF-8.
const b64 = toBase64(userInput);
const back = fromBase64(b64);
If you must render HTML from users, sanitize it first.
const clean = DOMPurify.sanitize(userInput, {USE_PROFILES:{html:true}});
demo.innerHTML = clean;