O'Reilly logo

Actionscript Cookbook by Joey Lott

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

9.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 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 ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required