Start learning free

LESSON 58 OF 410 · STRINGS I

Escape Characters in JavaScript Strings: Quotes, \n and \\

Lesson Read the full explanation

In JavaScript, some characters serve different functions and so cannot be displayed or printed like other characters. These characters are referred to as special characters.

For example, double quotes (") and single quotes (') are considered special characters by JavaScript. Their job is to let JavaScript know when a string declaration starts / ends.

That's why in the previous lesson we ran into problems when trying to have a single quote inside a string that is surrounded by single quotes.

console.log('My name's Andy');

We've found an elegant solution to this and that was by changing the type of quotes we surround our string in:

console.log("My name's Andy");

console.log('Double quotes "inside double" quotes');

But what if we wanted to print a string that contains both single and double quotes such as After "Coding 101" we'll solve some problems ?

Let's try to surround this text by single quotes:

console.log('After "Coding 101" we'll solve some problems');

That doesn't work. It produces a SyntaxError.

Maybe surrounding the text by double quotes will work:

console.log("After "Coding 101" we'll solve some problems");

Not really. It also produces a SyntaxError.

Character escaping comes to our rescue!


Escaping characters:

There is a way to print special characters like these in JavaScript, and that is by using the backslash character (\).

When we put \ before a special character, we tell JavaScript:

"Hey, I know this is a special character, but I don't want to use it like that here. I just want to print it like I print any other character."

For example, when putting a \ before a quote, JavaScript no longer interprets that as being the end of the string:

console.log('My name\'s Andy');

console.log("Double quotes \"inside double\" quotes");

console.log("After \"Coding 101\" we'll solve some problems");

console.log('After "Coding 101" we\'ll solve some problems');

The output of this code is:

My name's Andy
Double quotes "inside double" quotes
After "Coding 101" we'll solve some problems
After "Coding 101" we'll solve some problems

Escaping backslash:

Sometimes we might want to print strings that contain character \, such as a file path in your PC:

console.log('C:\Users\Andy\Games');

This code looks perfectly fine at first sight, but if you run it, it would produce this output:

C:UsersAndyGames

That's because in JavaScript, \ is also a special character and its main purpose is escaping other characters, not being printed.

So when the interpreter sees \U for example, it supposes that you are trying to escape character U, which is not a special character thus it's already "escaped".

Like any special character, \ can also be escaped by putting another \ in front of it (\\):

console.log('C:\\Users\\Andy\\Games');

The output of this code is:

C:\Users\Andy\Games

New line character:

Similarly, the escape sequence can be used to make an otherwise printable character serve a special function.

For example, the letter n can be printed normally, but adding a backslash before it (\n) will indicate the start of a new line:

console.log("Hello world!\nWhat a good day for coding!\n");
console.log("Let\'s have a blast!");

The output of this code is:

Hello world!
What a good day for coding!

Let's have a blast!

Notice the empty line after What a good day for coding! ?

That's one new line from the \n plus the new line that console.log() prints no matter what the message is.


Assignment
Follow the Coding Tutorial and let's escape some characters!


Hint
Look at the examples above if you get stuck.


STEP 1 OF 3
    Ctrl + Enter to check

    JAVASCRIPT · STRINGS I

    Escaping Characters in JavaScript, explained

    Why strings need escape characters

    Quotes mark where a string starts and ends, so a quote inside the text can be mistaken for the end. A backslash (\) placed before a character changes how JavaScript reads it. That backslash is the escape character, and the two characters together are an escape sequence. It lets you put quotes, backslashes and line breaks inside a string.

    The simplest way around the quote problem is to pick the other kind of quote for the outside:

    console.log("My name's Andy");
    console.log('Double quotes "inside single" quotes');
    

    That works until the text contains both kinds. In 'After "Coding 101" we'll solve some problems', the apostrophe in we'll ends the string early and the rest is a SyntaxError. The same happens with double quotes on the outside. Escaping solves it.

    Escaping quotes

    Put a backslash before the quote that should stay part of the text. JavaScript then reads it as an ordinary character:

    console.log('My name\'s Andy');
    console.log("Double quotes \"inside double\" quotes");
    console.log("After \"Coding 101\" we'll solve some problems");
    
    My name's Andy
    Double quotes "inside double" quotes
    After "Coding 101" we'll solve some problems
    

    The backslash is not part of the string. In "\"" the string holds one character, a double quote. You only need to escape the kind of quote that surrounds the string: an apostrophe inside double quotes can stay as it is.

    Escaping the backslash itself

    Since a backslash starts an escape sequence, a literal backslash has to be written as two:

    console.log('C:\\Users\\Andy\\Games');   // C:\Users\Andy\Games
    console.log('C:\Users\Andy\Games');      // C:UsersAndyGames
    

    In the second line each \U, \A and \G is read as an escape sequence that JavaScript does not define, and an unknown one simply stands for the character itself, so the backslash disappears. Worse, some letters after a backslash have a meaning of their own. A path like C:\Users\Andy\notion contains \n, which is a line break, so a single backslash would split the path in two lines. Doubling every backslash is the fix: \\ is one backslash.

    Common escape sequences

    WriteYou get
    \'a single quote
    \"a double quote
    \\one backslash
    \na new line
    \ta tab
    \ra carriage return
    \u0041the character with that code (here A)
    \u{1F600}a character by its code point, which also covers emoji
    \x41the character with that two-digit hexadecimal code (here A)

    New lines with \n

    The letter n prints as a normal letter, but \n is a line break. It lets one console.log print several lines:

    console.log("Hello world!\nWhat a good day for coding!\n");
    console.log("Let's have a blast!");
    
    Hello world!
    What a good day for coding!
    
    Let's have a blast!
    

    There is an empty line in the middle: the \n at the end of the first string ends the line, and console.log adds its own line break after every call. A \n counts as one character, so "a\nb".length is 3, while "a\\nb" (a backslash followed by an n) has length 4.

    Backticks and raw strings

    Template literals, which use backticks, can hold both kinds of quote without any escape, and they can run over several lines:

    console.log(`She said "it's fine"`);
    console.log(`line1
    line2`);
    

    A backtick inside a template literal is escaped like the others: \`. If you want backslashes to stay exactly as typed, tag the literal with String.raw: String.raw`C:\Users\Andy\notion` gives C:\Users\Andy\notion without doubling anything.

    The exercise, step by step

    1. A message with quotes. Print I'll study "Coding 101" on AlgoCademy. Wrap the text in double quotes. The apostrophe in I'll needs nothing, and each inner double quote gets a backslash.
    2. Two lines from one call. Print I will learn this and No matter what on separate lines using a single console.log. Put \n between them inside one string.
    3. A file path. Print C:\Users\Andy\notion. Each of the three backslashes is written as \\. This is the case where a single backslash would be dangerous, because \n in \notion would be a line break.
    console.log("I'll study \"Coding 101\" on AlgoCademy");
    console.log("I will learn this\nNo matter what");
    console.log("C:\\Users\\Andy\\notion");
    
    I'll study "Coding 101" on AlgoCademy
    I will learn this
    No matter what
    C:\Users\Andy\notion
    

    Common mistakes

    • Forgetting to double backslashes in Windows paths. Backslashes silently vanish or turn into tabs and line breaks. Doubling them, or using forward slashes ("C:/Users/Andy"), avoids the problem.
    • Escaping the wrong quote. In a double-quoted string, \' works, but it is unnecessary. The quote that matches the outside is the one that must be escaped.
    • Typing the escape as text. In "a\\nb" there is no line break: it prints a backslash and an n.

    Key takeaways

    • A backslash before a character changes its meaning: it turns quotes into plain text and letters such as n and t into line breaks and tabs.
    • Escape the quote that surrounds the string, or switch to the other kind of quote or to backticks.
    • Write \\ for a literal backslash.
    • \n is one character, a line break, and console.log adds another after the text.
    Keep going with JavaScriptAbout 340 step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free