Previous Page
Next Page

Recipe 12.2. Using Quotes and Apostrophes in Strings

Problem

You want to use quotes or apostrophes within a string value.

Solution

Use a backslash to escape the quotes or apostrophes contained within the string. Alternatively, use single quotes within double quotes, or vice versa.

Discussion

The ActionScript compiler tries to match u p quotes of the same kind (single quotes with single quotes and double quotes with double quotes) when processing string literals. Therefore, if you enclose a string literal within quotes of one type and also try to include the same kinds of quotes in the string value, the code fails to compile as you intended.

This string assignment causes an error because of mismatched quotes. In the following example, the string starts with a double quote ("Yes), therefore, the double quote character before the Y signals the end of the string to the compiler. As such, it does not understand what to do with the remaining characters:

var error:String = "He said, "Yes."";  // Incorrect.

One possible solution is to use single quotes to enclose a string literal that contains double quotes, or double quotes to enclose a string literal that contains single quotes, as follows:

// This assignment works. The result is a string: He said, "Yes."
var exampleA:String = 'He said, "Yes."';

// This assignment also works. The result is a string: He said, 'Yes.'
var exampleB:String = "He said, 'Yes.'";

However, if the string value contains both single and double quotes, this technique does not work. Furthermore, you have to pay close attention to what type of quotes are used when creating the strings, and you lose consistency in your program with constant quote switching. An alternative solution, which works all the time, is to use the backslash character (\\) to escape any quotes used within the string value (i.e., escape the quote by preceding it by a backslash):

// This assignment works. The result is a string: He said, "Yes."
var sExample:String = "He said, \"Yes.\"";

The backslash tells the compiler to interpret the next character literally, and not with any special meaning it might normally have. Therefore, when you precede a quotation mark within a string value with the backslash character, you tell the compiler that the quote does not signal the boundary of the string value, but rather it is to be interpreted as just another character in the string.


Previous Page
Next Page
Converted from CHM to HTML with chm2web Pro 2.85 (unicode)