LEARNING JAVASCRIPT - Trang 65

This

dialog

string will fail no matter which quotation mark we choose. Fortunately,

we can escape quotation marks with a backslash (

\

), which is a signal to JavaScript

that the string is not ending. Here’s the preceding example rewritten to use both types

of quotation marks:

const

dialog1

=

"He looked up and said \"don't do that!\" to Max."

;

const

dialog2

=

'He looked up and said "don\'t do that!" to Max.'

;

Then, of course, we get into the chicken-and-egg problem that arises when we want

to use a backslash in our string. To solve this problem, a backslash can escape itself:

const

s

=

"In JavaScript, use \\ as an escape character in strings."

;

Whether you use single or double quotes is up to you. I generally prefer double quo‐

tation marks when I’m writing text that might be presented to the user, because I use

contractions (like don’t) more often than I use double quotation marks. When I’m

expressing HTML inside a JavaScript string, I tend to prefer single quotation marks

so that I can use double quotation marks for attribute values.

Special Characters

The backslash is used for more than simply escaping quotation marks: it is also used

to represent certain nonprintable characters, such as newlines and arbitrary Unicode

characters.

Table 3-1

lists the commonly used special characters.

Table 3-1. Commonly used special characters

Code

Description

Example

\n

Newline (technically a line feed character: ASCII/Unicode
10)

"Line1\nLine2"

\r

Carriage return (ASCII/Unicode 13)

"Windows line 1\r\nWindows line 2"

\t

Tab (ASCII/Unicode 9)

"Speed:\t60kph"

\'

Single quote (note that you can use this even when not
necessary)

"Don\'t"

\"

Double quote (note that you can use this even when not
necessary)

'Sam said \"hello\".'

\`

Backtick (or “accent grave”; new in ES6)

`New in ES6: \` strings.`

\$

Dollar sign (new in ES6)

`New in ES6: ${interpolation}`

\\

Backslash

"Use \\\\ to represent \\!"

Special Characters | 41