Encapsulation Playground

Type any text (even tricky characters or HTML), then click “Transform”. This shows multiple safe representations and where each is appropriate.

HTML text node HTML attribute JSON string URL component Regex literal CSV field Base64 Sanitized HTML

HTML Text Node (textContent)

Safest way to inject user text into the DOM without interpreting as HTML.

Use when: displaying raw text in the page.

      
Demo
demo.textContent = userInput;

HTML Attribute (escapeAttribute)

Encodes characters problematic in attributes (quotes, ampersands, <,>).

Use when: building attributes like title="...".

      
Demo
Hover me (title attribute)
el.setAttribute("title", escapeAttribute(userInput));

JSON String Literal (JSON.stringify)

Produces a valid JSON string literal containing your text.

Use when: embedding text in JSON payloads.

      
Demo
const payload = { comment: userInput };
const json = JSON.stringify(payload);

URL Component (encodeURIComponent)

Percent-encodes a component for safe inclusion in URLs.

Use when: query strings, path segments.

      
Demo (attach as query)
const u = new URL("https://example.test/");
u.searchParams.set("q", userInput);
u.toString();

Regex Literal Escape

Escapes characters with special meaning in regular expressions.

Use when: constructing dynamic regex from user input.

      
Demo
const re = new RegExp(escapeForRegex(userInput), "g");

CSV Field

Double-quotes field and doubles inner quotes per RFC4180 practice.

Use when: emitting CSV rows.

      
Demo
// Emit a row with a single field:
const row = toCSVField(userInput);

Base64 (Unicode-safe)

Encodes arbitrary text (including Unicode) to Base64 via UTF-8.

Use when: transport that only accepts ASCII.

      
Demo
const b64 = toBase64(userInput);
const back = fromBase64(b64);

Sanitized HTML (DOMPurify)

If you must render HTML from users, sanitize it first.

Use when: rendering limited, safe HTML.

      
Demo (rendered)
const clean = DOMPurify.sanitize(userInput, {USE_PROFILES:{html:true}});
demo.innerHTML = clean;

Event Log