DTTooleras

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.

DevToolsHub Team18 min read520 words

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, "&lt;")
    .replace(/>/g, "&gt;")
    .replace(/"/g, "&quot;")
    .replace(/'/g, "&#39;");
}
element.textContent = userInput; // Even better — no escaping needed

The five characters that MUST be escaped in HTML:

CharacterEntityWhy
&&amp;Starts entity references
<&lt;Opens HTML tags
>&gt;Closes HTML tags
"&quot;Ends attribute values
'&#39;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 escapingxss preventionsql injectionhtml escapeurl encodingjson escapesecurity

Related articles

All articles

Practice with free tools

200+ free developer tools that run in your browser.

Browse all tools →