Skip to content
Encode & Decode 6 min read

String Escaping: JSON, JavaScript, HTML, and SQL

Learn why strings need escaping in different contexts, which characters to escape for JSON, JavaScript, HTML, and SQL, and how to do it safely to prevent injection attacks.

ToolsVito Team

Why Context-Specific Escaping Matters

The string He said "Hello" & she said 'Bye' needs to be escaped differently depending on where it appears:

  • In a JSON value: escape double quotes and backslashes
  • In an HTML attribute: encode &, ", <, >
  • In a JavaScript string literal: escape quotes and backslashes
  • In a SQL query: escape single quotes (or use parameterized queries)

Using the wrong escaping for the context is how injection attacks work. The golden rule: use parameterized queries for SQL and DOM APIs (not innerHTML) for HTML. Manual escaping is a fallback when those aren't available.

JSON Escaping

// Characters that must be escaped in JSON strings:
\"   → \\"    (double quote)
\\  → \\\\   (backslash)
\n   → \\n    (newline)
\r   → \\r    (carriage return)
\t   → \\t    (tab)
\u0000–\u001F → \\uXXXX  (control characters)

// Always use JSON.stringify — never manually escape
JSON.stringify({ message: 'He said "Hi"' })
// '{"message":"He said \\"Hi\\""}'

JavaScript String Escaping

// In single-quoted strings
'can\'t stop'     // escape apostrophe
'line1\nline2'   // escape newline

// In double-quoted strings
"say \"hi\""    // escape double quote

// Template literals — only backtick and $ need escaping
`cost is \$${amount}`

// Unicode escapes
"\u00e9"  // é
"\u{1F600}"  // 😀 (ES6 full Unicode escape)

SQL Escaping (and Why Parameterized Queries Are Better)

-- NEVER DO THIS — SQL injection vulnerability
const query = "SELECT * FROM users WHERE name = '" + userInput + "'";
-- If userInput = "'; DROP TABLE users; --"
-- The query becomes: SELECT * FROM users WHERE name = ''; DROP TABLE users; --'

-- ALWAYS DO THIS — parameterized query
// Node.js with pg
const result = await pool.query(
  "SELECT * FROM users WHERE name = $1",
  [userInput]  // driver handles escaping
);

// Node.js with mysql2
connection.execute("SELECT * FROM users WHERE name = ?", [userInput]);

Shell/Command Escaping

// Node.js — never construct shell commands with user input
// Use execFile (no shell) instead of exec (shell interpolation)

// BAD
exec(`convert ${filename} output.png`);  // command injection if filename = "x; rm -rf /"

// GOOD
execFile("convert", [filename, "output.png"]);  // no shell, args are not interpolated

Escape Strings Instantly

Use ToolsVito's String Escaper to escape or unescape strings for JSON, JavaScript, HTML, and SQL — paste and copy.

Try it now — free, runs in your browser

String Escaper

Escape for JSON, JS, HTML, SQL