How to Escape String Literals
Learn how to escape string literals: which characters need escaping, how rules differ by language and format, and how to verify the result with a round-trip check.
Escaping a string literal means rewriting text so a programming language or data format reads it back exactly as you intended. If you paste a Windows path, a quotation or a multi-line message directly between quotes, some characters may end the string early, turn into something else, or cause a syntax error. An escaped string uses special sequences, usually starting with a backslash, to represent those characters safely. This guide explains what escaping does, which characters need it in common contexts, and how to produce and verify an escaped string without changing its meaning.
What escaping does to your text
A string literal is text written directly in source code or a data file, enclosed in delimiters such as double quotes, single quotes or backticks. The parser needs to know where the string starts and ends, and how to represent characters you cannot type or see easily. Escaping solves both problems.
The input is raw text: the exact characters you want the program to hold. The output is a longer representation of that same text, in which certain characters are replaced by escape sequences. An escape sequence is a short code, such as \n for a newline or " for a double quote, that the parser converts back into the original character. When the program runs, the value in memory is identical to the raw text; only the way it is written in the source changes.
Characters that typically need escaping fall into three groups:
- The delimiter itself, such as a double quote inside a double-quoted string.
- The escape character, usually the backslash, because a lone backslash would be read as the start of a sequence.
- Control and invisible characters, such as newline, carriage return, tab and other characters that would break the line or be hard to see.
Scope matters. Escaping rules belong to a specific context, such as JSON, Python, JavaScript, a shell or an SQL dialect. A string escaped correctly for one context can be wrong in another, so the first decision is always where the text will be used.
Common escape sequences by context
The table below summarizes widely documented rules. Always check the reference for your exact language version or engine, because details differ.
| Context | Delimiter handling | Backslash | Newline and tab | Unicode escapes |
| JSON | " inside double-quoted strings; single quotes are not delimiters and ' is not a valid escape | \ | \n, \t (raw control characters U+0000 to U+001F are not allowed) | \uXXXX; characters outside the Basic Multilingual Plane are written as two \u escapes (a surrogate pair) |
| Python | " or ' depending on quote style | \ | \n, \t | \xhh, \uXXXX, \UXXXXXXXX, \N{name} |
| JavaScript | " or '; in template literals, escape the backtick and the ${ sequence | \ | \n, \t | \xhh, \uXXXX, \u{X...} |
| Standard SQL | Double the single quote: 'It''s' | Not special in the standard, but some engines (for example MySQL in its default mode) treat it as an escape character | Usually written as a literal line break | Depends on the engine |
| POSIX shell, single quotes | No escapes work inside; close the quote, add an escaped quote, reopen: 'It'''s' | Literal inside single quotes | Literal line break inside quotes | Not applicable |
How to produce an escaped string step by step
Prerequisites: know the target context (language, format or engine), have the original text available in its exact form, and know the encoding of any file you read it from, which is UTF-8 in most modern workflows. Then follow these steps.
- 1. Keep the original. Work on a copy so you can compare and recover if something goes wrong.
- 2. Identify the target context and its delimiter. Choosing a quote style that does not appear in the text can reduce how much escaping you need.
- 3. Escape backslashes first. Replace each \ with \. Doing this later would double-escape the backslashes you add in the next steps.
- 4. Escape the delimiter. Replace each occurrence of the chosen quote character with its escaped form, such as " in JSON, Python or JavaScript.
- 5. Escape control characters. Replace newline with \n, carriage return with \r and tab with \t, plus any other characters your context forbids in raw form.
- 6. Decide how to handle non-ASCII characters. Either keep them as-is if the file encoding supports them, or convert them to Unicode escapes if the target requires ASCII-only text.
- 7. Wrap the result in the delimiters and verify it with a round-trip check, described below.
Doing this by hand is error-prone. Where possible, let the language or a dedicated tool generate the escaped form, because built-in serializers apply the rules in the correct order.
Before-and-after example
Illustrative example. The original text has two lines. The first contains double quotes and a backslash. Between the lines is a single newline character (LF), shown here as an actual line break:
She said "Use C:\temp"
Next line
Correction to the display above: because code blocks preserve characters exactly, the raw text is better shown without any escaping at all. The two raw lines are:
She said "Use C:\temp"
Next line
Escaped as a JSON string, or as a double-quoted Python or JavaScript literal, the same text becomes a single line:
"She said \"Use C:\\temp\"\nNext line"
In a single-quoted Python or JavaScript literal, the double quotes no longer need escaping, but the backslash and newline still do:
'She said "Use C:\\temp"\nNext line'
Why the backslash matters: if you write "C:\temp" without doubling the backslash in Python, JavaScript or JSON, the parser reads \t as a tab character. The resulting value would be C, colon, a tab, then emp, which silently changes your content instead of raising an error.
Generating and checking the result in code
A round-trip check confirms the escaping is correct: escape the text, parse the escaped form back, and compare it with the original. If they match exactly, nothing meaningful was changed. The snippets below are illustrative; the comments describe documented behavior, so run them in your own environment to confirm.
Python, using the standard json module:
import json
original = 'She said "Use C:\\temp"\nNext line'
escaped = json.dumps(original)
print(escaped) # the escaped JSON string
assert json.loads(escaped) == original # round-trip check
JavaScript, using the built-in JSON object:
const original = 'She said "Use C:\\temp"\nNext line';
const escaped = JSON.stringify(original);
console.log(escaped); // the escaped JSON string
console.log(JSON.parse(escaped) === original); // should print true
Note one documented difference: Python's json.dumps converts non-ASCII characters to \uXXXX escapes by default (pass ensure_ascii=False to keep them), while JavaScript's JSON.stringify leaves most non-ASCII characters unescaped. Both outputs are valid JSON and parse back to the same value, but they look different.
For a Python source literal rather than JSON, repr() produces a valid Python representation of a string, and ast.literal_eval() parses it back for a round-trip check.
Raw strings and alternatives to escaping
Many languages offer literal forms that reduce or remove the need for backslash escaping:
- Python raw strings, written r"...", treat backslashes literally, which is convenient for paths and regular expressions. A raw string still cannot end with an odd number of backslashes.
- JavaScript template literals, written with backticks, allow real line breaks inside the string; you still need to escape backticks and the ${ sequence.
- C# verbatim strings, written @"...", treat backslashes literally and represent a double quote by doubling it: "".
- For SQL, parameterized queries avoid manual escaping entirely by passing values separately from the query text, which also protects against SQL injection.
Pitfalls that change content unintentionally
- Double escaping: running an already escaped string through an escaper again turns \n into \n, so the output shows a literal backslash and n instead of a line break. Escape raw text exactly once.
- Layered contexts: a regular expression inside a string literal needs both regex escaping and string escaping. To match one literal backslash with a regex written in an ordinary JavaScript or Java string, you write four backslashes; a Python raw string needs only two.
- Newline style: text copied from Windows often contains CRLF (\r\n) rather than LF (\n). Escaping preserves whichever you have, producing \r\n in the output. Normalize line endings first only if the carriage returns are not meaningful.
- Encoding: reading a file with the wrong encoding corrupts characters before escaping even starts. Confirm the source encoding, then escape.
- Mixing contexts: JSON escaping is not shell escaping, and Python escaping is not SQL escaping. Escape for the context where the text is finally parsed, and if text passes through several layers, apply each layer's rules from the innermost outward.
Quick verification checklist
- The escaped string parses without a syntax error in the target context.
- Parsing it back returns a value identical to the original, including whitespace, line endings and capitalization.
- No backslash sequence was created by accident, such as \t inside a path.
- The original text is still saved separately in case you need to start over.
Evidence note: no tool-specific documentation, benchmarks or version details were supplied for this guide. The rules above reflect generally documented behavior of the named languages and formats; confirm edge cases against the reference for the exact version or engine you use.