Backslash Escape Sequences in Strings

Learn how backslash escape sequences work in programming strings. Understand the backslash as an escape character, common sequences like \\n, \\t, and \\\\, and how to handle literal backslashes across languages.

Basic Escaping

Detailed Explanation

Backslash Escape Sequences

The backslash (\\) is the universal escape character in most programming languages. When placed before certain characters inside a string, it changes the meaning of that character from a literal to a control instruction.

How Backslash Escaping Works

In a string literal, the compiler or interpreter reads characters sequentially. When it encounters a backslash, it does not output the backslash itself. Instead, it reads the next character and interprets the two-character combination as a single special character or instruction.

\\n  → newline (line feed, U+000A)
\\t  → horizontal tab (U+0009)
\\\\  → literal backslash
\\0  → null character (U+0000)
\\'  → literal single quote
\\"  → literal double quote

The Backslash Itself

Because the backslash acts as an escape initiator, representing a literal backslash requires escaping it with another backslash: \\\\. This is one of the most common sources of confusion, particularly when building file paths on Windows:

// Wrong — \\n is a newline, not part of the path
const path = "C:\\new_folder\\test";

// Correct — each \\\\ produces one literal backslash
const path = "C:\\\\new_folder\\\\test";

Language Differences

Most C-family languages (C, C++, Java, JavaScript, C#) share the same core set of backslash escapes. Python adds raw strings (r"...") that treat backslashes literally. Go requires all escape sequences to be valid — an unrecognized \\z is a compile error rather than a pass-through.

Escaping in Regular Expressions

Regular expressions add a second layer of escaping. A regex that matches a literal backslash needs \\\\\\\\ in a normal string because the string layer consumes one pair, and the regex layer consumes the other.

Common Pitfalls

  • File paths on Windows: Use forward slashes or raw strings instead of double-escaping every separator.
  • JSON strings: Backslashes must always be escaped (\\\\), and only a limited set of sequences (\\n, \\t, \\", \\\\, \\/, \\b, \\f, \\r, \\uXXXX) is valid.
  • Copy-paste errors: Copying escaped strings between environments can introduce or strip escape layers.

Use Case

Understanding backslash escaping is essential for every developer. It comes up when writing file paths, building regex patterns, constructing JSON payloads, generating SQL queries, creating shell commands, and anywhere a string must represent characters that are not directly typeable or that conflict with the string delimiter syntax.

Try It — String Escape/Unescape

Open full tool