String Escaping in Programming: When, Why, and How
A comprehensive guide to string escaping — why it matters for security, how different languages handle it, and practical examples for JSON, HTML, SQL, URLs, and regex.
Why String Escaping Matters
String escaping is the process of replacing special characters with safe representations. Without proper escaping, you risk:
- XSS attacks — Unescaped HTML allows script injection
- SQL injection — Unescaped SQL allows database manipulation
- Broken JSON — Unescaped quotes break JSON parsing
- Broken URLs — Special characters corrupt URL structure
- Regex errors — Unescaped metacharacters change pattern meaning
HTML Escaping (XSS Prevention)
The most critical escaping for web developers. Any user input displayed in HTML must be escaped:
// ❌ DANGEROUS — XSS vulnerability
element.innerHTML = userInput;
// ✅ SAFE — HTML entities
function escapeHtml(str) {
return str
.replace(/&/g, "&")
.replace(/</g, "<")
.replace(/>/g, ">")
.replace(/"/g, """)
.replace(/'/g, "'");
}
element.textContent = userInput; // Even better — no escaping needed
The five characters that MUST be escaped in HTML:
| Character | Entity | Why |
|---|---|---|
& | & | Starts entity references |
< | < | Opens HTML tags |
> | > | Closes HTML tags |
" | " | Ends attribute values |
' | ' | Ends attribute values |
Use our HTML Entity Encoder to escape HTML content, or our String Escape/Unescape tool for multiple formats.
JSON Escaping
JSON strings must escape these characters:
" → \"
\ → \\
/ → \/ (optional)
\b → backspace
\f → form feed
\n → newline
\r → carriage return
\t → tab
\uXXXX → unicode character
// JavaScript handles this automatically
JSON.stringify("Hello \"World\"\nNew line");
// '\"Hello \\\"World\\\"\\nNew line\"'
Format and validate JSON with our JSON Formatter.
SQL Escaping (Injection Prevention)
Never concatenate user input into SQL queries. Use parameterized queries instead:
// ❌ SQL INJECTION VULNERABILITY
const query = `SELECT * FROM users WHERE name = '${userInput}'`;
// ✅ SAFE — Parameterized query
const query = `SELECT * FROM users WHERE name = $1`;
const result = await db.query(query, [userInput]);
If you must escape manually (not recommended):
' → '' (single quote doubled)
\ → \\
URL Escaping
URLs can only contain ASCII characters. Special characters must be percent-encoded:
space → %20
& → %26
= → %3D
? → %3F
# → %23
/ → %2F
encodeURIComponent("hello world & friends");
// "hello%20world%20%26%20friends"
Use our URL Encoder/Decoder for URL escaping.
Regex Escaping
Regular expression metacharacters must be escaped with backslash when used literally:
. * + ? ^ $ { } ( ) | [ ] \
// Escape a string for use in a regex
function escapeRegex(str) {
return str.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
}
const userSearch = "price is $10.00";
const regex = new RegExp(escapeRegex(userSearch));
Test your regex patterns with our Regex Tester.
Related Tools
- String Escape/Unescape — Escape for JSON, JS, HTML, URL, CSV, SQL, XML, Regex
- HTML Entity Encoder — Encode/decode HTML entities
- URL Encoder/Decoder — Encode/decode URLs
- JSON Formatter — Format and validate JSON
- Regex Tester — Test regex patterns
- Base64 Encoder — Encode binary data as text