3.2.1 String Literals
A string is a sequence of zero or more Unicode characters enclosed within single or double quotes (' or "). Double-quote characters may be contained within strings delimited by single-quote characters, and single-quote characters may be contained within strings delimited by double quotes. String literals must be written on a single line; they may not be broken across two lines. If you need to include a newline character in a string literal, use the character sequence \n , which is documented in the next section. Examples of string literals are:
"" // The empty string: it has zero characters 'testing' "3.14" 'name="myform"' "Wouldn't you prefer O'Reilly's book?" "This string\nhas two lines" "pi is the ratio of a circle's circumference to its diameter"
Note that when you use single quotes to delimit your strings, you must be careful with English contractions and possessives like can't and O'Reilly's. Since the apostrophe is the same as the single-quote character, you must use the backslash character (\) to escape any apostrophes that appear in single-quoted strings (this is explained in the next section).
<a href="" onclick="alert('Thank you')">Click Me</a>
3.2.2 Escape Sequences in String Literals
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'
3.2.3 Working with Strings
msg = "Hello, " + "world"; // Produces the string "Hello, world" greeting = "Welcome to my home page," + " " + name;
last_char = s.charAt(s.length - 1)
sub = s.substring(1,4);
i = s.indexOf('a');
There are quite a few other methods that you can use to manipulate strings. You'll find full documentation of these methods in the core reference section of this book, under the String object and subsequent listings.
last_char = s[s.length - 1];
Note, however, that this syntax is not part of the ECMAScript v3 standard, is not portable, and should be avoided.