How String Escaping Works in JSON, JavaScript, HTML, SQL and Regex

Why quotes, backslashes and newlines need escaping, the rules for each format from JSON to CSV, and how to avoid double escaping and injection bugs.

Updated September 29, 2026 6 min read

Use the free String Escape / UnescapeEscape or unescape text for JSON, JavaScript, Java, HTML, SQL, CSV and regex

A config file stops parsing because a description contains a double quote. A CSV import splits one address across three columns because of commas. A search box crashes when someone types a parenthesis, because the text was dropped into a regular expression. A log shows \\n where you expected a line break. These are all escaping problems.

This guide explains what escaping is, why every format has its own rules, how the most common ones work, and how to avoid the two classic failures: forgetting to escape and escaping twice.

Why escaping exists

Every text format reserves a few characters for its own structure. JSON uses " to mark where a string ends. HTML uses < to start a tag. SQL uses ' around string values. CSV uses , between fields.

When your data contains one of those characters, the parser cannot tell whether it is structure or content. Escaping solves this by replacing the character with a sequence that the format defines as "this is data":

  • In JSON, " inside a string becomes \".
  • In HTML, < in text becomes &lt;.
  • In SQL, ' inside a string becomes ''.
  • In CSV, a field containing a comma is wrapped in quotes.

Unescaping reverses the process to get the original text back. The key idea is that escaping belongs to a context. The same text needs different escaping depending on where it is going.

The rules for common formats

JSON strings

JSON requires escaping for the double quote, the backslash and control characters (code points below U+0020). Newlines become \n, tabs \t, and other control characters \u00XX. Everything else, including accented letters and emoji, can appear as-is in UTF-8.

In JavaScript, never build JSON by gluing strings together. JSON.stringify applies the rules correctly:

const note = 'Line 1\nShe said "ok"\tC:\\temp';
console.log(JSON.stringify(note));
// "Line 1\nShe said \"ok\"\tC:\\temp"

JavaScript, Java and C# string literals

These follow the same backslash tradition as C: \\, \", \', \n, \r, \t, plus \uXXXX for any character. In JavaScript you only need to escape the quote character you used to delimit the string, and template literals (backticks) additionally need \` and \${. Java and C# source files are often limited to ASCII by team convention, so non-ASCII characters are written as \uXXXX.

HTML and XML

HTML escaping uses entities: &amp; for &, &lt; for <, &gt; for >, &quot; for " and &#39; for '. Escape all five whenever untrusted text goes into HTML content or an attribute. This is the core defence against cross-site scripting (XSS). XML has exactly five predefined entities, the same set with &apos; for the apostrophe. For converting a wider range of symbols to named entities, the HTML entity encoder covers the full list.

SQL string literals

Standard SQL escapes a single quote by doubling it: O'Brien becomes 'O''Brien'. Some databases also accept backslash escapes, which is one reason manual SQL escaping is fragile. In application code, use parameterised queries (placeholders like ? or $1) and let the driver handle values. Manual escaping is fine for writing one-off scripts or seed files by hand.

CSV fields

RFC 4180 CSV wraps a field in double quotes when it contains a comma, a double quote or a line break, and doubles any quotes inside: Acme, Inc. becomes "Acme, Inc.", and 27" monitor becomes "27"" monitor".

Regular expressions

Regex metacharacters . * + ? ^ $ { } ( ) | [ ] \ have special meanings. To match a user's text literally, put a backslash in front of each one:

const escapeRegExp = (s) => s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
const pattern = new RegExp(escapeRegExp("Total (USD): $5.00"));
console.log(pattern.test("Invoice Total (USD): $5.00")); // true

Without escaping, $5.00 would be read as "end of line, then 5, any character, 0, 0". Test patterns in a regex tester before shipping them.

URL components

Query values and path segments use percent-encoding: each unsafe byte becomes % plus two hex digits. encodeURIComponent("R&D costs = 50%") returns R%26D%20costs%20%3D%2050%25. The URL encoder handles whole URLs and components, and the article on percent-encoding explains the rules in depth.

Escape or unescape text in the browser

The String Escape / Unescape tool applies these rules for nine formats and shows the result as you type.

  1. Open String Escape / Unescape and pick a Format: JSON string, JavaScript string, Java / C# string, HTML, XML, SQL string, CSV field, Regular expression or URL component. A hint underneath describes exactly what that format escapes.
  2. Choose Escape or Unescape.
  3. For JavaScript escaping, set Quotes to escape to All, Double only, Single only or Backtick only, depending on how your string literal is quoted.
  4. Paste your text into Raw text (or Escaped text when unescaping). Click Sample to try a string full of awkward characters.
  5. Copy the Escaped result or click Download to save it as a text file.

When unescaping JSON or URLs, the tool reports malformed input, such as a lone backslash or a % not followed by two hex digits, rather than guessing.

Pitfalls and how to avoid them

Double escaping

The most common bug is escaping text that is already escaped. \n becomes \\n, &amp; becomes &amp;amp;, and users see the escape codes on screen. It usually happens when two layers each try to be helpful: a template engine that escapes HTML automatically, plus a manual escape before it. Decide which layer owns escaping for each context and do it exactly once, as late as possible, right before the text is inserted.

Escaping for the wrong context

HTML escaping does not make text safe inside a <script> block, a CSS value or a URL. Inserting user input into a JavaScript string inside HTML needs JavaScript escaping first; a URL inside an href needs URL encoding and then HTML attribute escaping. Each nesting level adds a layer.

Backslashes in code that builds regexes

In a JavaScript string, "\d" is just d, because \d is not a recognised string escape. To build the regex \d+ from a string, you must write "\\d+". Regex literals (/\d+/) avoid this extra layer.

Windows paths

C:\new\temp in a JSON or JavaScript string contains \n and \t, which turn into a newline and a tab. Escape the backslashes or use forward slashes, which Windows APIs generally accept.

Unicode and invisible characters

JavaScript strings treat U+2028 and U+2029 (line and paragraph separators) specially in some older engines, so escaping them is safer when generating code. Control characters pasted from word processors are also worth stripping; tools like the JSON formatter will point out where a stray character breaks parsing.

Frequently asked questions

How do I escape a double quote in JSON?

Put a backslash before it: \". If you are generating JSON from code, use your language's JSON library so quotes, backslashes and newlines are all handled.

What is the difference between escaping and encoding?

Escaping marks special characters so a parser reads them as data within the same format. Encoding, such as Base64 or percent-encoding, transforms the whole value into a different representation. The terms overlap, and URL encoding is often called escaping.

How do I escape a single quote in SQL?

Double it: 'It''s'. In application code, use parameterised queries instead of escaping values yourself.

Why do I see \n instead of a line break?

The text has been escaped twice, or a literal backslash-n was stored as data. Unescape it once, then find which layer added the extra escaping.

Does HTML escaping prevent all XSS?

It prevents it in normal HTML content and quoted attributes. Values placed into scripts, styles, URLs or event handler attributes need escaping for those contexts too, or should be avoided entirely.

Try it now: String Escape / Unescape

Loading tool…