Course contentsShow
← JavaScript
Lesson 146 of 2,7235. StringsFree lesson

Escape Sequences in Strings

Use backslash notation to include special characters like newlines, tabs, and quotes.

Escape Sequences in Strings

What you'll learn: How to include special characters like quotes, newlines, and tabs inside your strings using backslash notation.

The Problem with Special Characters

Sometimes you need to put characters in a string that would otherwise confuse JavaScript. For example, how do you include a quote mark inside a string that's already wrapped in quotes? Or how do you create a line break without actually pressing Enter in your code?

The Backslash to the Rescue

JavaScript uses the backslash (\) as an escape character. When JavaScript sees a backslash inside a string, it knows the next character has a special meaning.

Here are the most common escape sequences:

  • \' — single quote
  • \" — double quote
  • \\ — backslash itself
  • \n — newline (line break)
  • \t — tab
  • \r — carriage return

Examples in Action

let quote = "She said, \"Hello!\"";
// Output: She said, "Hello!"

let path = "C:\\Users\\Documents\\file.txt";
// Output: C:\Users\Documents\file.txt

let multiLine = "First line\nSecond line\nThird line";
// Output: First line
//         Second line
//         Third line

let tabbed = "Name:\tJohn\nAge:\t25";
// Output: Name:    John
//         Age:     25

Think of It Like Whispering

Imagine the backslash is you leaning over to JavaScript and whispering, "Hey, the next character isn't what it looks like—it's special." Without that whisper, JavaScript would misinterpret quotes as the end of your string or get confused by other special characters.

Key Takeaway: Use a backslash (\) before special characters to include them literally in strings or to insert invisible formatting characters like newlines and tabs.