3.2.2. Escape Sequences in String Literals
The backslash character (\) has a
special purpose in JavaScript strings.
Combined with the character that follows it, it represents a
character that is not otherwise representable within the string. For
example,
\n is an escape sequence that
represents a newline character.[6]
Another example, mentioned in the previous section, is the
\' escape, which represents the single quote (or
apostrophe) character. This escape sequence is useful when you need
to include an apostrophe in a string literal that is contained within
single quotes. You can see why we call these escape
sequences -- here, the backslash allows us to escape from the
usual interpretation of the single-quote character. Instead of using
it to mark the end of the string, we use it as an apostrophe:
'You\'re right, it can\'t be a quote'
Table 3-2 lists the JavaScript escape sequences
and the characters they represent. Two of the escape sequences are
generic ones that can be used to represent any character by
specifying its
Latin-1 or Unicode character code as
a hexadecimal number. For example, the sequence
\xA9 represents the copyright symbol, which has
the Latin-1 encoding given by the hexadecimal number A9. Similarly,
the \u escape represents an arbitrary Unicode
character specified by four hexadecimal digits.
\u03c0 represents the character
, for
example. Note that Unicode escapes are required by the
ECMAScript v1 standard but are not
typically supported in implementations prior to JavaScript 1.3. Some
implementations of JavaScript also allow a Latin-1 character to be
specified by three octal digits following a backslash,
but this escape sequence is not
supported in the ECMAScript v3
standard and should no longer be used.
Table 3-2. JavaScript escape sequences
Sequence
|
Character represented
|
\0
|
The NUL character (\u0000).
|
\b
|
Backspace (\u0008).
|
\t
|
Horizontal tab (\u0009).
|
\n
|
Newline (\u000A).
|
\v
|
Vertical tab (\u000B).
|
\f
|
Form feed (\u000C).
|
\r
|
Carriage return (\u000D).
|
\"
|
Double quote (\u0022).
|
\'
|
Apostrophe or single quote (\u0027).
|
\\
|
Backslash (\u005C).
|
\xXX
|
The Latin-1 character specified by the two hexadecimal digits
XX.
|
\uXXXX
|
The Unicode character specified by the four hexadecimal digits
XXXX.
|
\XXX
|
The Latin-1 character specified by the octal digits
XXX, between 1 and 377. Not supported by
ECMAScript v3; do not use this escape sequence.
|
Finally, note that the backslash escape cannot be used before a line
break to continue a string (or other JavaScript) token across two
lines or to include a literal line break in a string. If the
\ character precedes any character other than
those shown in Table 3-2, the backslash is simply
ignored (although future versions of the language may, of course,
define new escape sequences). For example, \# is
the same thing as #.