Ctrl + K
Encoding18 min read

How Escape Sequences Work

A practical guide to escape sequences, explaining how special characters are represented in strings, source code, JSON, HTML, and regular expressions.

Published: 2026-10-05

Escape sequences are a way of representing characters or special values that cannot be written directly, would be difficult to type, or would otherwise be interpreted as syntax. They appear throughout programming languages, configuration files, data formats, regular expressions, and other text-processing systems.

A familiar example is \n, which commonly represents a line feed inside a string literal. Other common sequences include \t for a tab, \" for a quotation mark, and \\ for a literal backslash.

Escape sequences are often confused with encoding. They are related concepts, but they are not the same thing. An escape sequence is usually a textual representation interpreted by a language or format, while an encoding such as UTF-8 defines how characters are represented as bytes.

What Is an Escape Sequence?

An escape sequence is a special sequence of characters that tells a parser, compiler, interpreter, or data format to interpret those characters in a special way.

const message = "Hello\nWorld";

The two characters backslash and n in the source code are interpreted as a line feed in the resulting string. They do not normally represent two separate characters in the final value.

const message = "Hello\nWorld";

console.log(message);

// Hello
// World

The exact syntax and available escape sequences depend on the language or format. JavaScript, Python, JSON, regular expressions, shell languages, and HTML all have different escaping rules.

Why Escape Sequences Are Needed

Programming languages use certain characters as syntax. A quotation mark can delimit a string, a backslash can introduce an escape sequence, and a newline may terminate a statement or have another special meaning.

If you need one of these characters as literal data, you may need to escape it so that the parser does not interpret it as syntax.

const message = "She said \"hello\".";

The quotation marks around hello are part of the string value. They are escaped in the source so that they do not terminate the surrounding string literal.

The Backslash Is Commonly Used for Escaping

Many programming languages use the backslash character as the escape introducer. The character following the backslash determines what special meaning is requested.

SequenceTypical meaning
\nLine feed
\rCarriage return
\tHorizontal tab
\bBackspace
\fForm feed
\vVertical tab
\\Literal backslash
\"Literal double quote
\'Literal single quote in languages that support it
\0Null character in supported contexts

These meanings are common but should not be assumed to be identical in every language. Always check the syntax supported by the specific language or format.

Escape Sequences Are Not Universal

One of the most important rules is that an escape sequence only has meaning in a context that defines it.

For example, \n commonly represents a line feed in programming-language string literals, but the same two characters can simply be ordinary text in another context.

ContextEscape syntax
JavaScript string\n commonly represents a line feed
JSON string\n represents a line feed
Python string\n commonly represents a line feed
Regex\n commonly matches or represents a line feed depending on context
HTML\n in source does not generally mean the same thing as a JavaScript string escape

Common Escape Sequences in JavaScript

JavaScript supports a number of escape sequences inside string literals and template literals. Some represent control characters, while others allow characters that would otherwise conflict with string syntax.

const text = "Line 1\nLine 2";
const tab = "Name:\tAlice";
const quote = "She said \"Hi\".";
const slash = "C:\\Users\\Alice";

The source contains escape sequences, but the resulting strings contain the represented characters.

Newline: \n

The \n escape sequence commonly represents a line feed, U+000A.

const text = "First line\nSecond line";

console.log(text);

This produces a string containing a line feed between the two visible lines.

Carriage Return: \r

The \r escape sequence commonly represents carriage return, U+000D.

const value = "A\rB";

CR and LF are separate characters. A Windows-style CRLF line ending consists of both characters in sequence and can be represented as \r\n in a JavaScript string.

const windowsLine = "First line\r\nSecond line";

Tab: \t

The \t escape sequence commonly represents a horizontal tab, U+0009.

const row = "Alice\t25\tDeveloper";

A tab is not the same character as several spaces. An application can display the tab at a configurable width.

Escaping Quotes

Quotation marks are frequently escaped because they delimit string literals.

const doubleQuote = "She said \"hello\".";
const singleQuote = 'It\'s working.';

The escape allows the quote to become part of the string instead of ending the string literal.

Escaping the Backslash

Because the backslash introduces escape sequences, a literal backslash often needs to be escaped with another backslash.

const path = "C:\\Users\\Alice\\Documents";

The source contains doubled backslashes, while the resulting string contains ordinary backslash characters.

Why \\ Is Needed

Without escaping, a backslash followed by another character may be interpreted as the beginning of an escape sequence. Writing \\ explicitly tells the parser that a literal backslash is intended.

Unicode Escape Sequences

Unicode escape sequences provide a textual way to represent Unicode characters using code points or code units, depending on the syntax and language.

const letter = "\u0041";

console.log(letter);
// A

Here, \u0041 represents U+0041, which is the Unicode code point for the Latin capital letter A.

The \uXXXX Form

Many programming languages use a form based on \u followed by four hexadecimal digits.

const text = "\u0048\u0065\u006C\u006C\u006F";

console.log(text);
// Hello

Each four-digit sequence represents a Unicode value in the range supported by that syntax. The exact interpretation can differ between languages, especially for characters outside the Basic Multilingual Plane.

Unicode Code Points vs UTF-8

A Unicode escape sequence is not the same thing as UTF-8 encoding. A Unicode escape represents a character or code value textually, while UTF-8 specifies how Unicode characters are represented as bytes.

RepresentationExample for APurpose
Literal characterADirect text representation
Unicode escape\u0041Textual escape representation
UTF-8 bytes41Byte representation
HTML entityAHTML character reference

These representations can refer to the same character while serving completely different purposes.

Unicode Escapes for Characters Outside the BMP

Unicode contains characters beyond the Basic Multilingual Plane. In JavaScript, the traditional \uXXXX escape syntax represents a UTF-16 code unit, so characters outside the BMP may require surrogate pairs.

const symbol = "\uD83D\uDE00";

console.log(symbol);
// 😀

The two UTF-16 code units together represent the Unicode character U+1F600, GRINNING FACE.

Modern JavaScript also supports Unicode code point escapes using \u{...}, which makes characters outside the BMP easier to represent.

const symbol = "\u{1F600}";

console.log(symbol);
// 😀

Hexadecimal Escape Sequences

Some languages support hexadecimal escapes that represent a character using a numeric value written in hexadecimal notation.

const letter = "\x41";

console.log(letter);
// A

In JavaScript, \x followed by two hexadecimal digits represents a character based on the resulting value. This is different from the four-digit \u form.

SyntaxExampleResult
\xHH\x41A
\uHHHH\u0041A
\u{H...}\u{41}A

Escape Sequences in JSON

JSON defines a specific set of escape sequences for strings. JSON strings use double quotes, so quotation marks and backslashes need escaping when they are part of the string value.

{
  "message": "She said \"hello\".",
  "path": "C:\\Users\\Alice",
  "line": "First\nSecond"
}

JSON supports escapes such as \" for quotation marks, \\ for backslashes, \n for line feed, \r for carriage return, \t for tabs, and \u followed by four hexadecimal digits for Unicode values.

JSON Escaping vs JavaScript Escaping

JSON and JavaScript string literals look similar, but they are not identical language constructs. JSON has a deliberately defined set of valid escape sequences.

A string that is valid JavaScript source is not automatically valid JSON. This distinction becomes important when data is sent through APIs or stored in JSON files.

Double Escaping

One of the most confusing escape-related problems occurs when a string is itself embedded inside another escaped representation. In that situation, a backslash may need to be escaped more than once.

const value = "\\n";

This source represents a string containing the two characters backslash and n rather than an actual newline. The extra backslash prevents \n from being interpreted as a newline escape.

The same principle becomes even more important when JSON is embedded inside JavaScript, a regular expression is stored in JSON, or a string passes through multiple serialization layers.

Escaping in Regular Expressions

Regular expressions have their own special characters and escape rules. Characters such as ., *, +, ?, (, ), [, ], {, }, ^, $, and | can have special meanings depending on their position.

\.

The escaped dot means that the literal period should be matched rather than the regex wildcard meaning of an unescaped dot.

Regex Escaping Is Different from String Escaping

A regular expression can have two layers of escaping when it is written inside a programming-language string. The programming language processes the string first, and the regex engine then processes the resulting pattern.

const pattern = "\\d+";
const regex = new RegExp(pattern);

console.log(regex.test("123"));
// true

The JavaScript string contains the regex pattern \d+, so the regex engine receives the backslash required by the digit character class.

When a regex is written as a JavaScript regular-expression literal, the additional JavaScript string-escaping layer is not involved in the same way.

const regex = /\d+/;

Escaping HTML

HTML uses character references rather than the backslash-based escape syntax commonly found in programming languages. Characters such as <, >, &, and quotes can be represented using named or numeric HTML entities when necessary.

<p>&lt;strong&gt;Hello&lt;/strong&gt;</p>

Here, &lt; represents the less-than character. This is HTML escaping, not a programming-language escape sequence.

CharacterHTML representation
<&lt;
>&gt;
&&amp;
"&quot;
'&#39;

Escaping vs Encoding

Escaping and encoding are often used interchangeably in casual conversation, but they solve different problems.

ConceptPurposeExample
EscapingPrevent syntax from being interpreted as syntax\"
Unicode escapingRepresent a character using a Unicode escape\u0041
HTML escapingRepresent HTML-sensitive characters safely&lt;
URL encodingRepresent URL data safely%20
UTF-8 encodingRepresent Unicode text as bytesA → 41

The same visible character can therefore have several different representations depending on where it is being used.

Escape Sequences and Source Code

Escape sequences allow source code to contain characters that would otherwise be difficult or impossible to write directly in a particular literal.

const text = "Path:\tFolder\nFile.txt";

The source is compact and explicit. The resulting string contains a tab and a line feed.

Escape Sequences and Raw Strings

Some languages and syntaxes provide raw-string forms that reduce or disable ordinary escape processing. These are especially useful for regular expressions, Windows paths, and long strings containing many backslashes.

pattern = r"\d+"
path = r"C:\Users\Alice"

The exact behavior of raw strings varies by language. A raw-string syntax does not necessarily mean that every character loses all special meaning.

Common Escape Sequence Mistakes

  • Forgetting that backslash starts an escape sequence.
  • Using a language's escape syntax in a different language or format.
  • Confusing Unicode escapes with UTF-8 encoding.
  • Forgetting the second escaping layer when generating a regex from a string.
  • Adding unnecessary escaping where the target format does not require it.
  • Incorrectly escaping JSON embedded inside another string.
  • Assuming that HTML entities work like backslash escapes.
  • Confusing a literal backslash followed by n with an actual newline.

Literal \n vs an Actual Newline

One of the most common sources of confusion is the difference between the two characters backslash and n and the single line-feed character.

const escaped = "\\n";
const newline = "\n";

console.log(escaped.length);
// 2

console.log(newline.length);
// 1

The first string contains a backslash followed by n. The second contains a single line-feed character.

Inspecting Escape Sequences

When debugging escaping problems, inspect the actual string rather than relying only on how it is displayed.

const value = "Hello\nWorld";

console.log(JSON.stringify(value));
// "Hello\nWorld"

console.log([...value].map(char => char.codePointAt(0)));
// [72, 101, 108, 108, 111, 10, 87, 111, 114, 108, 100]

The code-point inspection reveals that the newline is represented by value 10, which is U+000A.

Escaping and Serialization

Serialization converts data into a representation that can be stored or transmitted. Escaping is often part of serialization because the serialized representation needs to remain syntactically valid.

const data = {
  message: "Hello\nWorld"
};

const json = JSON.stringify(data);

console.log(json);
// {"message":"Hello\nWorld"}

The newline in the JavaScript value is represented using an escape sequence in the JSON text so that the resulting JSON remains valid on one logical line.

Escaping Does Not Change the Underlying Character

An escape sequence is usually a representation of a character rather than a new character with a special identity. After parsing, the resulting string contains the represented character.

For example, the JavaScript source \u0041 and the literal character A can produce strings with the same character content.

const a = "A";
const b = "\u0041";

console.log(a === b);
// true

Escape Sequences and Unicode

Unicode escapes are especially useful when source code needs to represent characters that are difficult to type, when a file needs a portable textual representation, or when a format explicitly requires escaped Unicode values.

However, escaping every non-ASCII character is not automatically better. Modern source files can normally use UTF-8 directly, making many Unicode characters readable without escapes.

When Should You Escape Characters?

  • When a character would otherwise terminate a string literal.
  • When a control character must be represented inside a string.
  • When the target format requires escaped syntax.
  • When a Unicode character needs a portable escaped representation.
  • When special regex characters must be matched literally.
  • When serialized data must remain syntactically valid.

When Should You Avoid Unnecessary Escaping?

Unnecessary escaping can make source code harder to read. If a character can safely and clearly be written directly, escaping it may provide no practical benefit.

const message = "Привет, мир!";

Modern UTF-8 source files can represent Unicode text directly, so there is usually no need to replace every non-ASCII character with Unicode escape sequences.

Security and Escaping

Escaping is an important part of safely placing data into some syntactic contexts, but escaping alone is not a universal security mechanism.

For example, HTML escaping can help prevent data from being interpreted as HTML markup when inserted into HTML text. JavaScript string escaping addresses a different context, and SQL parameterization addresses yet another one.

⚠️ Never assume that escaping a value for one context makes it safe for another. HTML, JavaScript, URLs, CSS, SQL, JSON, and regular expressions have different syntax and different escaping rules.

Context Matters

The same input may require different handling depending on where it is inserted. A value intended for a JSON string should be serialized as JSON. A value inserted into HTML should use the appropriate HTML escaping or DOM APIs. A value used in a regex pattern may need regex-specific escaping.

Target contextTypical approach
JavaScript stringJavaScript string escaping or serialization
JSONJSON serialization and JSON escaping
HTML textHTML escaping or safe DOM APIs
URL componentURL encoding
Regex patternRegex escaping
UTF-8 bytesCharacter encoding rather than escaping

Escape Sequences in Shell Commands

Shell languages also have quoting and escaping rules. A backslash can prevent a shell metacharacter from being interpreted specially, while quotation marks change how characters are processed.

echo "Hello\tWorld"
echo "A\$B"

Shell escaping is particularly context-sensitive because the shell performs parsing before the invoked program receives its arguments.

Escape Sequences in URLs

URL encoding is sometimes called escaping, but it uses percent encoding rather than the backslash syntax found in many programming languages.

hello world
↓
hello%20world

The %20 representation is a URL-encoded space. It should not be confused with the JavaScript string escape \x20 or the Unicode escape \u0020, even though all can represent the same underlying character in different contexts.

A Useful Mental Model

A simple way to understand escaping is to separate three layers: source representation, parsed text, and encoded bytes.

LayerExample
Source representation\u0041
Parsed characterA
UTF-8 byte representation41

The source representation tells a parser how to construct the text. The parsed text is the actual character data. Encoding then determines how that text is represented as bytes for storage or transmission.

Frequently Asked Questions

What is an escape sequence?

An escape sequence is a special textual sequence interpreted by a programming language or data format to represent a character or special value. Common examples include \n for a line feed, \t for a tab, and \\ for a literal backslash.

What does \n mean?

In many programming languages and formats, \n represents the line-feed character U+000A. It is important to distinguish the escape sequence from the literal two-character text consisting of a backslash and n.

What does \u0041 mean?

\u0041 is a Unicode escape representation that commonly produces the character A, whose Unicode code point is U+0041.

Is escaping the same as encoding?

No. Escaping is usually a syntax-level representation used by a language or format, while encoding defines how data is represented according to a particular encoding scheme, such as UTF-8.

Why do I sometimes need two backslashes?

Because the backslash often introduces an escape sequence. To represent a literal backslash, the source syntax commonly requires another backslash to escape it.

Why are regexes sometimes double-escaped?

When a regex is written inside a programming-language string, the string parser processes escapes first and the regex engine processes the resulting pattern afterward. A backslash may therefore need to survive both parsing layers.

Are Unicode escapes better than writing Unicode characters directly?

Not necessarily. Modern UTF-8 source files can normally contain Unicode characters directly. Escapes are useful when a format requires them or when an explicit escaped representation improves portability or readability.

Does HTML use backslash escapes?

HTML generally uses character references such as &lt; and &amp; rather than the backslash-based escape syntax commonly used in programming-language strings.

Helpful Encoding and Text Tools

Escape-related problems often involve several layers of text representation, so dedicated tools can make those transformations easier to inspect and verify. String escape tools can convert special characters to and from programming-language escape sequences, while Unicode escape converters can convert between characters and their Unicode escape representations. JSON escape tools are useful for encoding and decoding JSON string content, and HTML encoder and decoder tools can convert HTML-sensitive characters and entities.

Regex testers can also help when escaped characters are part of a regular-expression pattern, making it possible to verify whether the resulting pattern matches the intended text.

Conclusion

Escape sequences provide a compact way to represent characters that have special meanings or are difficult to write directly. Common examples such as \n, \t, \" and \\ appear throughout programming languages and data formats.

Unicode escapes extend the same idea to Unicode characters, while JSON, HTML, URLs, and regular expressions use their own escaping or encoding mechanisms. These systems may look similar but should not be treated as interchangeable.

The most useful distinction is between representation layers. An escape sequence is part of source or serialized text, the parser converts that representation into character data, and an encoding such as UTF-8 can then represent that character data as bytes.

Once these layers are kept separate, many seemingly confusing problems with backslashes, Unicode escapes, JSON, regular expressions, and encoded text become much easier to understand and debug.

Found an issue?

Found an error, outdated information, or something missing from this article? Let me know through the Contact page.

Your feedback helps improve our articles and keep them accurate and useful.