String Escaping Guide: JSON, HTML, URL, and More
String Escaping Guide: JSON, HTML, URL, and More
String escaping is one of those things you don't think about until it breaks your code, corrupts your data, or creates a security vulnerability.
Why Escaping Matters
Every context (JSON, HTML, SQL, URLs, regex, shell) has characters with special meaning. Escaping converts those characters into a safe representation for that context.
Failing to escape causes:JSON Escaping
Characters that must be escaped in JSON strings:
| Character | Escaped |
|-----------|---------|
| " | \\" |
| \\ | \\\\ |
| newline | \\n |
| tab | \\t |
| backspace | \\b |
| form feed | \\f |
| carriage return | \\r |
// JavaScript handles this automatically:
JSON.stringify('He said "hello"'); // '"He said \\"hello\\""'
HTML Escaping
Prevents XSS by converting HTML-special characters to entities:
function escapeHtml(str) {
return str
.replace(/&/g, "&")
.replace(/
.replace(/>/g, ">")
.replace(/"/g, """)
.replace(/'/g, "'");
}
Context matters: escaping for HTML attributes is different from HTML content. Inside an onclick attribute, you need JavaScript escaping AND HTML escaping.
URL Escaping
encodeURIComponent("hello world & goodbye");
// "hello%20world%20%26%20goodbye"
SQL Escaping
Don't escape SQL manually. Use parameterized queries:// Bad — SQL injection risk
db.query(SELECT * FROM users WHERE name = '${userInput}');
// Good — parameterized
db.query("SELECT * FROM users WHERE name = ?", [userInput]);
Shell Escaping
Shell commands are dangerous with user input:
Dangerous: user input could contain ; rm -rf /
grep "$USER_INPUT" file.txt
Safer: single quotes prevent expansion
grep '$USER_INPUT' file.txt
But the safest approach is to use your language's subprocess API with array arguments instead of shell strings.
Regex Escaping
Special regex characters that need escaping: . * + ? ^ $ { } [ ] ( ) | \\
function escapeRegex(str) {
return str.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
}
Try It
Use our String Escape/Unescape tool to convert strings between JSON, HTML, URL, XML, CSV, and C/Java escape formats.
Conclusion
Every output context has its own escaping rules. Use the language's built-in escaping functions, parameterize SQL queries, and never concatenate user input into shell commands. When in doubt, escape.