DekGenius.com
[ Team LiB ] Previous Section Next Section

Recipe 9.2 Using Quotes and Apostrophes in Strings

9.2.1 Problem

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

9.2.2 Solution

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

9.2.3 Discussion

The ActionScript interpreter always matches up quotes of the same kind (single quotes with single quotes and double quotes with double quotes) when used in strings. Therefore, if you enclose a string literal within quotes of one type and try to include the same kinds of quotes in the string value, ActionScript fails to interpret it as you intended.

This string assignment causes an error because of mismatched quotes. Flash interprets the " character before the Y as the end of the string; it does not understand what to do with the remaining characters.

myString = "He said, "Yes."";  // Wrong!

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:

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

// This assignment also works. The result is a string: He said, 'Yes.'
myString = "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 where. An alternative solution, which will work all the time, is to use the backslash to escape any quote used within the string value (i.e., escape the quote by preceding it by the backslash character):

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

The backslash character tells the ActionScript interpreter 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 ActionScript interpreter that the quote does not signal the boundary of the string value, as it normally would.

    [ Team LiB ] Previous Section Next Section