GameParticles
Developer

Escape Characters Explained: Backslashes, JSON and HTML

Escape characters let you write quotes, newlines and other special symbols inside strings. See the backslash escape table and how JSON, code and HTML differ.

Updated

An escape character is a marker that changes the meaning of the character that follows it. In most programming languages and in JSON the escape character is the backslash, so \n stands for a newline and \" stands for a literal double quote instead of the end of the string. Escaping exists because some characters are either impossible to type inside a string or already have a job in the syntax around it.

Why escaping is needed

A string in code is wrapped in quotes. That raises two problems straight away:

  • How do you put a quote inside it? In "She said "hi"" the parser sees the string end at the second quote.
  • How do you include characters you cannot see or type on one line, such as a newline or a tab?

The answer in both cases is an escape sequence: the escape character plus one or more characters that together stand for something else. "She said \"hi\"" is one string, and "line one\nline two" contains a line break. Since the backslash now has a special role, a literal backslash has to be escaped too, as \\.

Common backslash escapes

EscapeMeaningJSONJavaScriptPythonC
\nNewline (line feed)YesYesYesYes
\rCarriage returnYesYesYesYes
\tTabYesYesYesYes
\\BackslashYesYesYesYes
\"Double quoteYesYesYesYes
\'Single quoteNoYesYesYes
\bBackspaceYesYesYesYes
\fForm feedYesYesYesYes
\vVertical tabNoYesYesYes
\0Null characterNoYesYesYes
\xHHCharacter by two hex digitsNoYesYesYes
\uXXXXUnicode character by four hex digitsYesYesYesYes

\r\n together is the Windows line ending; \n alone is the Unix one. \u00e9 is the letter é, and \u20ac is the euro sign. Characters beyond four hex digits, such as most emoji, need \u{1F600} in JavaScript, \U0001F600 in Python, or a surrogate pair of two \u escapes in JSON.

Differences between languages and formats

The idea is shared, but the details are not, and most escaping bugs live in those details.

JSON

JSON is the strictest. Inside a string exactly two characters must always be escaped, the double quote and the backslash, along with every control character below U+0020, which covers newline, tab and carriage return. The only escapes allowed are \", \\, \/, \b, \f, \n, \r, \t and \uXXXX. Anything else, including \' and \x41, is a syntax error. A Windows path must be written "C:\\Users\\ada".

A literal line break inside a JSON string is also invalid; it has to be \n. That is a frequent cause of parse failures when multi-line text is pasted into a JSON value. The JSON formatting and validation guide covers the error messages you will see.

JavaScript

JavaScript accepts all the escapes in the table in both single- and double-quoted strings. Template literals, written with backticks, can contain real line breaks, and need escaping only for the backtick itself and for a dollar sign that is followed by an opening brace. An unknown escape such as \d in an ordinary string silently becomes d, which is why regular expressions built from strings need doubled backslashes: new RegExp("\\d+").

Python

Python adds \N{EURO SIGN} to name a character and \U with eight hex digits. Its raw strings, written r"C:\Users\ada", turn escaping off so backslashes stay literal, which is the usual way to write regular expressions and Windows paths. An unrecognized escape is kept as written, backslash included, with a warning in recent versions.

Formats that do not use the backslash

  • SQL string literals escape a single quote by doubling it: 'O''Brien'. Never build queries by escaping user input by hand; use parameterized queries.
  • CSV wraps a field in double quotes and doubles any quote inside: "5"" screen".
  • URLs use percent-encoding: a space becomes %20 and & becomes %26.
  • Regular expressions use the backslash to make a metacharacter literal, so \. matches a real dot. The regex cheat sheet lists them.

HTML entities versus string escapes

HTML has its own escaping system, and it is unrelated to backslashes. A browser does not interpret \n or \" in page content; it would display them as typed. Instead HTML uses entities, which start with an ampersand and end with a semicolon.

CharacterEntityWhy it is escaped
<&lt;Would start a tag
>&gt;Would end a tag
&&amp;Would start an entity
"&quot;Would end a double-quoted attribute
'&#39;Would end a single-quoted attribute

Entities come in three forms: named (&copy;), decimal numeric (&#169;) and hexadecimal numeric (&#xA9;). All three produce the copyright sign.

The two systems serve different layers. String escapes tell a programming language or data format what characters a string contains. HTML entities tell a browser to show a character as text instead of treating it as markup. Text often passes through both: a product name such as Fish & "Chips" is written "Fish & \"Chips\"" inside JSON, and becomes Fish &amp; &quot;Chips&quot; when placed into a page. Applying the wrong one, or the right one twice, leaves stray backslashes or &amp;amp; visible to users. Skipping the HTML step when showing user input is the root of cross-site scripting.

Escape for the place the text is going, at the moment it goes there. Store the original, unescaped value; escape it for JSON when building JSON, and for HTML when building HTML.

Escaping and unescaping text

The String Escape tool converts text in both directions for five targets: JSON, JavaScript, Regex, URL and HTML. Paste raw text to get a version that is safe to drop between quotes, or paste an escaped string from a log to read what it really says. Its HTML mode handles the five characters in the table above.

For named symbols such as &copy;, &euro; or &nbsp;, use the HTML Entity Encoder. It encodes either the five essential characters or a wider set of symbols, decodes named and numeric entities back to text, and includes a reference list of common entities.

Try it

Paste a string with quotes, a Windows path and a line break into the String Escape tool, pick JSON, and compare the output with the table at the top. Then switch to Unescape and paste a \"-heavy string from an API log to see the original text.

Tools in this guide

Frequently asked questions

What is an escape character?

An escape character is a symbol that tells a parser to treat the character after it differently from normal. In most programming languages it is the backslash: \n means a newline rather than the letter n, and \" means a literal quote rather than the end of the string.

How do I escape a double quote in JSON?

Put a backslash in front of it: \". JSON strings must also escape the backslash itself as \\ and write control characters such as newlines and tabs as \n and \t. Single quotes need no escaping in JSON.

What is the difference between \n and \r\n?

\n is a line feed, the line ending used by Linux and macOS. \r\n is a carriage return followed by a line feed, the line ending used by Windows and required by protocols such as HTTP. Most editors and languages handle both.

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

The text was escaped twice. A real newline was first written as \n, then that backslash was escaped again when the string was placed inside another string. Unescape the value once, or fix the code that encodes it a second time.

More developer guides

JSON Formatter
Developer · Format, validate and minify JSON with syntax highlighting.
↵
Base64 Encode / Decode
Developer · Encode text to Base64 or decode Base64 back to plain text.
↵
URL Encoder / Decoder
Developer · Encode or decode URL components and query strings.
↵
Hash Generator
Developer · Generate MD5, SHA-1, SHA-256 and SHA-512 hashes.
↵
UUID Generator
Developer · Generate UUIDs v4 (random) in bulk with one click.
↵
Regex Tester
Developer · Test regular expressions against text with live match highlighting.
↵
Word Counter
Text · Count words, characters, sentences, paragraphs and reading time.
↵
Case Converter
Text · Convert text between UPPER, lower, Title, camelCase, snake_case and more.
↵
List Sorter
Text · Sort, reverse, deduplicate and shuffle lists of text.
↵
Markdown Preview
Text · Write Markdown and see a live rendered preview side by side.
↵
Percentage Calculator
Numbers · Calculate percentages, increases, decreases and what % one number is of another.
↵
Color Converter
Colors · Convert colors between HEX, RGB, HSL and HSV instantly.
↵
Snake
Arcade · Eat food, grow longer, don't hit the walls. A timeless classic.
↵
2048
Puzzle · Slide tiles and combine them to reach the legendary 2048 tile.
↵
Word Grid
Puzzle · Guess the hidden five letter word in six tries using color clues.
↵
Sudoku
Puzzle · Fill the 9x9 grid with logic. Four difficulties from easy to expert.
↵
Minesweeper
Strategy · Use number clues to clear the minefield. Classic logic, three levels.
↵
Breakout
Arcade · Smash every brick with paddle and ball. Power-ups, combos, endless levels.
↵
Typing Practice
Casual · Build your WPM and accuracy with timed drills from 30 seconds to 5 minutes. Find your weak keys.
↵
TypeRunner
Arcade · Multiplayer typing race. Race friends by link, beat computer runners, or chase your own ghost.
↵
Typing Blocks
Arcade · Type each word before its wooden block lands. Miss, and the pile climbs toward the line.
↵
Bubble Shooter
Arcade · Aim, bank shots off the walls, and pop groups of three or more bubbles.
↵
Road Rush
Arcade · Race seven rivals through traffic and punch your way to the front.
↵