Java Reference
In-Depth Information
What if you want a string with a single quote mark in the middle, say a string like Peter O'Toole?
If you enclose it in double quotes, you'll be fi ne, so “Peter O'Toole” is recognized by JavaScript.
However, 'Peter O'Toole' will produce an error. This is because JavaScript thinks that your text
string is Peter O (that is, it treats the middle single quote as marking the end of the string) and falls
over wondering what the Toole' is.
Another way around this is to tell JavaScript that the middle ' is part of the text and is not indicating
the end of the string. You do this by using the backslash character (\), which has special meaning in
JavaScript and is referred to as an escape character . The backslash tells the browser that the next character
is not the end of the string, but part of the text. So 'Peter O\'Toole' will work as planned.
What if you want to use a double quote inside a string enclosed in double quotes? Well, everything
just said about the single quote still applies. So 'Hello “Paul”' works, but “Hello “Paul”” won't.
However, “Hello \”Paul\”” will also work.
JavaScript has a lot of other special characters, which can't be typed in but can be represented using the
escape character in conjunction with other characters to create escape sequences . These work much the
same as in HTML. For example, more than one space in a row is ignored in HTML, so a space is repre-
sented by the term  . Similarly, in JavaScript there are instances where you can't use a character
directly but must use an escape sequence. The following table details some of the more useful escape
sequences.
Escape Sequences
Character Represented
\b
Backspace
\f
Form feed
\n
New line
\r
Carriage return
\t
Tab
\'
Single quote
\”
Double quote
\\
Backslash
\xNN
NN is a hexadecimal number that identifi es a character in the Latin-1
character set.
The least obvious of these is the last, which represents individual characters by their character num-
ber in the Latin-1 character set rather than by their normal appearance. Let's pick an example: Say you
wanted to include the copyright symbol (©) in your string. What would your string need to look like?
The answer is “\xA9 Paul Wilton” .
Similarly, you can refer to characters using their Unicode escape sequence. These are written \u NNNN ,
where NNNN refers to the Unicode number for that particular character. For example, to refer to the
copyright symbol using this method, you use the string \u00A9 .
Search WWH ::




Custom Search