This guide is protected under copyright law, furnished for informational use only, is subject to change without notice, and should not be construed as a
commitment by Adobe Systems Incorporated. Adobe Systems Incorporated assumes no responsibility or liability for any errors or inaccuracies that may appear
in the informational content contained in this guide.
This guide is licensed for use under the terms of the Creative Commons Attribution Non-Commercial 3.0 License. This License allows users to copy, distribute,
and transmit the guide for noncommercial purposes only so long as (1) proper attribution to Adobe is given as the owner of the guide; and (2) any reuse or
distribution of the guide contains a notice that use of the guide is governed by these terms. The best way to provide notice is to include the following link. To
view a copy of this license, visit
http://creativecommons.org/licenses/by-nc-sa/3.0/
Adobe, the Adobe logo, Acrobat, Acrobat Capture, Acrobat Connect, Acrobat Messenger, Acrobat 3D Capture, ActionScript, ActiveTest, Adobe ActionSource,
Adobe AIR, Adobe AIR logo, Adobe Audition, Adobe Caslon, Adobe Connect, Adobe DataWarehouse, Adobe Dimensions, Adobe Discover, Adobe Financial
Services, Adobe Garamond, Adobe Genesis, Adobe Griffo, Adobe Jenson, Adobe Kis, Adobe OnLocation, Adobe Originals logo, Adobe PDF logo, Adobe
Premiere, AdobePS, Adobe SiteSearch, Adobe Type Manager, Adobe Wave, Adobe Wave logo , Adobe WebType, Adobe Wood Type, After Effects, AIR , Alexa,
Andreas, Arno, ATM, Authorware, Balzano, Banshee, Benson Scripts, Better by Adobe. , Bickham Script, Birch, Blackoak, Blue Island, Brioso, BusinessCatalyst,
Buzzword, Caflisch Script, Cairngorm, Calcite, Caliban, Captivate, Carta, Chaparral, Charlemagne, Cheq, Classroom in a Book, ClickMap, Co-Author,
ColdFusion, ColdFusion Builder, Conga Brava, Contribute, Copal, Coriander, Cottonwood, Creative Suite, Critter, Cronos, CS Live, Custom Insight,
CustomerFirst, Cutout, Digital Pulse, Director, Distiller, DNG logo, Dreamweaver, DV Rack, Encore, Engaging beyond the Enterprise, ePaper, Ex Ponto,
Fireworks, Flash, Flash logo, Flash Access, Flash Access logo, Flash Builder, Flash Cast , FlashCast, Flash Catalyst, FlashHelp, Flash Lite, Flash on., FlashPaper,
Flash Platform Services logo , Flex, Flex Builder, Flood, Font Folio, Frame , FrameCenter, FrameConnections, FrameMaker, FrameManager, FrameViewer,
FreeHand, Fusaka, Galahad, Giddyup, Giddyup Thangs, GoLive, GoodBarry, Graphite, HomeSite, HBX, HTML Help Studio, HTTP Dynamic Streaming logo ,
Hypatia, Illustrator, ImageReady, Immi 505, InCopy, InDesign, Ironwood, Jimbo, JRun, Juniper, Kazuraki, Kepler, Kinesis, Kozuka Gothic, Kozuka Mincho,
Kuler, Leander Script, Lens Profile Creator logo , Lightroom, Lithos, LiveCycle, Macromedia, Madrone, Mercado, Mesquite, Mezz, Minion, Mojo, Montara,
Moonglow, MXML, Myriad, Mythos, Nueva, Nyx, 1-Step RoboPDF, Omniture, Open Screen Project, Open Source Media Framework logo, OpenType logo,
Ouch!, Ovation, PageMaker, PageMaker Portfolio, PDF JobReady, Penumbra, Pepperwood, Photoshop, Photoshop logo, Pixel Bender, Poetica, Ponderosa,
Poplar, Postino, PostScript, PostScript logo, PostScript 3, PostScript 3i, Powered by XMP, Prana, PSPrinter, Quake, Rad, Reader, Real-Time Analytics, Reliq,
RoboEngine, RoboHelp, RoboHTML, RoboLinker, RoboPDF, RoboScreenCapture, RoboSource Control, Rosewood, Roundtrip HTML, Ryo, Sanvito, Sava,
Scene7, See What’s Possible , Script Teaser, Shockwave, Shockwave Player logo, Shuriken Boy, Silentium, Silicon Slopes, SiteCatalyst, SiteCatalyst NetAverages,
Software Video Camera, Sonata, Soundbooth, SoundEdit, Strumpf, Studz, Tekton, Test&Target, 360Code, Toolbox, Trajan, TrueEdge, Type Reunion, Ultra,
Utopia, Vector Keying, Version Cue, VirtualTrak, Visual Call, Visual Communicator, Visual Sciences, Visual Sensor, Visual Server, Viva, Voluta , Warnock,
Waters Titling, Wave , Willow, XMP logo, Zebrawood are either registered trademarks or trademarks of Adobe Systems Incorporated in the United States and/or
other countries.
Android is a trademark of Google Inc. ActiveX and Windows are either registered trademarks or trademarks of Microsoft Corporation in the United States and
other countries. Macintosh is a trademark of Apple Inc., registered in the United States and other countries. Java is a trademark or registered trademark of Sun
Microsystems, Inc. in the United States and other countries. All other trademarks are the property of their respective owners.
Updated Information/Additional Third Party Code Information available at http://www.adobe.com/go/thirdparty.
Portions include software under the following terms:
This product includes software developed by the Apache Software Foundation (http://www.apache.org/).
MPEG Layer-3 audio compression technology licensed by Fraunhofer IIS and Thomson Multimedia (http://www.mp3licensing.com).
This software is based in part on the work of the Independent JPEG Group.
Speech compression and decompression technology licensed from Nellymoser, Inc. (www.nellymoser.com).
This product contains either BSAFE and/or TIPEM software by RSA Security, Inc.
Sorenson Spark™ video compression and decompression technology licensed from Sorenson Media, Inc.
Adobe Systems Incorporated, 345 Park Avenue, San Jose, California 95110, USA
Notice to U.S. Government End Users: The Software and Documentation are “Commercial Items,” as that term is defined at 48 C.F.R. §2.101, consisting of
“Commercial Computer Software” and “Commercial Computer Software Documentation,” as such terms are used in 48 C.F.R. §12.212 or 48 C.F.R. §227.7202,
as applicable. Consistent with 48 C.F.R. §12.212 or 48 C.F.R. §§227.7202-1 through 227.7202-4, as applicable, the Commercial Computer Software and
Commercial Computer Software Documentation are being licensed to U.S. Government end users (a) only as Commercial Items and (b) with only those rights
as are granted to all other end users pursuant to the terms and conditions herein. Unpublished-rights reserved under the copyright laws of the United States.
Adobe agrees to comply with all applicable equal opportunity laws including, if appropriate, the provisions of Executive Order 11246, as amended, Section 402
of the Vietnam Era Veterans Readjustment Assistance Act of 1974 (38 USC 4212), and Section 503 of the Rehabilitation Act of 1973, as amended, and the
regulations at 41 CFR Parts 60-1 through 60-60, 60-250, and 60-741. The affirmative action clause and regulations contained in the preceding sentence shall be
incorporated by reference.
Chapter 64: SQL error detail messages, ids, and arguments
xiii
Last updated 3/21/2011
Chapter 1: Working with dates and times
Flash Player 9 and later, Adobe AIR 1.0 and later
Timing might not be everything, but it's usually a key factor in software applications. ActionScript 3.0 provides
powerful ways to manage calendar dates, times, and time intervals. Two main classes provide most of this timing
functionality: the Date class and the new Timer class in the flash.utils package.
Dates and times are a common type of information used in ActionScript programs. For instance, you might need to
know the current day of the week or to measure how much time a user spends on a particular screen, among many
other possibilities. In ActionScript, you can use the Date class to represent a single moment in time, including date and
time information. Within a Date instance are values for the individual date and time units, including year, month, date,
day of the week, hour, minutes, seconds, milliseconds, and time zone. For more advanced uses, ActionScript also
includes the Timer class, which you can use to perform actions after a certain delay or at repeated intervals.
More Help topics
Date
1
flash.utils.Timer
Managing calendar dates and times
Flash Player 9 and later, Adobe AIR 1.0 and later
All of the calendar date and time management functions in ActionScript 3.0 are concentrated in the top-level Date
class. The Date class contains methods and properties that let you handle dates and times in either Coordinated
Universal Time (UTC) or in local time specific to a time zone. UTC is a standard time definition that is essentially the
same as Greenwich Mean Time (GMT).
Creating Date objects
Flash Player 9 and later, Adobe AIR 1.0 and later
The Date class boasts one of the most versatile constructor methods of all the core classes. You can invoke it four
different ways.
First, if given no parameters, the Date() constructor returns a Date object containing the current date and time, in
local time based on your time zone. Here’s an example:
var now:Date = new Date();
Second, if given a single numeric parameter, the Date() constructor treats that as the number of milliseconds since
January 1, 1970, and returns a corresponding Date object. Note that the millisecond value you pass in is treated as
milliseconds since January 1, 1970, in UTC. However, the Date object shows values in your local time zone, unless you
use the UTC-specific methods to retrieve and display them. If you create a new Date object using a single milliseconds
parameter, make sure you account for the time zone difference between your local time and UTC. The following
statements create a Date object set to midnight on the day of January 1, 1970, in UTC:
Last updated 3/21/2011
ACTIONSCRIPT 3.0 DEVELOPER’S GUIDE
Working with dates and times
var millisecondsPerDay:int = 1000 * 60 * 60 * 24;
// gets a Date one day after the start date of 1/1/1970
var startTime:Date = new Date(millisecondsPerDay);
Third, you can pass multiple numeric parameters to the Date() constructor. It treats those parameters as the year,
month, day, hour, minute, second, and millisecond, respectively, and returns a corresponding Date object. Those input
parameters are assumed to be in local time rather than UTC. The following statements get a Date object set to midnight
at the start of January 1, 2000, in local time:
var millenium:Date = new Date(2000, 0, 1, 0, 0, 0, 0);
Fourth, you can pass a single string parameter to the Date() constructor. It will try to parse that string into date or
time components and then return a corresponding Date object. If you use this approach, it’s a good idea to enclose the
Date() constructor in a try..catch block to trap any parsing errors. The Date() constructor accepts a number of
different string formats (which are listed in the
ActionScript 3.0 Reference for the Adobe Flash Platform). The
following statement initializes a new Date object using a string value:
var nextDay:Date = new Date("Mon May 1 2006 11:30:00 AM");
If the Date() constructor cannot successfully parse the string parameter, it will not raise an exception. However, the
resulting Date object will contain an invalid date value.
2
Getting time unit values
Flash Player 9 and later, Adobe AIR 1.0 and later
You can extract the values for various units of time within a Date object using properties or methods of the Date class.
Each of the following properties gives you the value of a time unit in the Date object:
• The fullYear property
• The month property, which is in a numeric format with 0 for January up to 11 for December
• The date property, which is the calendar number of the day of the month, in the range of 1 to 31
• The day property, which is the day of the week in numeric format, with 0 standing for Sunday
• The hours property, in the range of 0 to 23
• The minutes property
• The seconds property
• The milliseconds property
In fact, the Date class gives you a number of ways to get each of these values. For example, you can get the month
value of a Date object in four different ways:
• The month property
• The getMonth() method
• The monthUTC property
• The getMonthUTC() method
All four ways are essentially equivalent in terms of efficiency, so you can use whichever approach suits your
application best.
The properties just listed all represent components of the total date value. For example, the milliseconds property
will never be greater than 999, since when it reaches 1000 the seconds value increases by 1 and the milliseconds
property resets to 0.
Last updated 3/21/2011
ACTIONSCRIPT 3.0 DEVELOPER’S GUIDE
Working with dates and times
If you want to get the value of the Date object in terms of milliseconds since January 1, 1970 (UTC), you can use
getTime() method. Its counterpart, the setTime() method, lets you change the value of an existing Date
the
object using milliseconds since January 1, 1970 (UTC).
Performing date and time arithmetic
Flash Player 9 and later, Adobe AIR 1.0 and later
You can perform addition and subtraction on dates and times with the Date class. Date values are kept internally in
terms of milliseconds, so you should convert other values to milliseconds before adding them to or subtracting them
from Date objects.
If your application will perform a lot of date and time arithmetic, you might find it useful to create constants that hold
common time unit values in terms of milliseconds, like the following:
public static const millisecondsPerMinute:int = 1000 * 60;
public static const millisecondsPerHour:int = 1000 * 60 * 60;
public static const millisecondsPerDay:int = 1000 * 60 * 60 * 24;
Now it is easy to perform date arithmetic using standard time units. The following code sets a date value to one hour
from the current time using the
getTime() and setTime() methods:
3
var oneHourFromNow:Date = new Date();
oneHourFromNow.setTime(oneHourFromNow.getTime() + millisecondsPerHour);
Another way to set a date value is to create a new Date object using a single milliseconds parameter. For example, the
following code adds 30 days to one date to calculate another:
// sets the invoice date to today's date
var invoiceDate:Date = new Date();
// adds 30 days to get the due date
var dueDate:Date = new Date(invoiceDate.getTime() + (30 * millisecondsPerDay));
Next, the millisecondsPerDay constant is multiplied by 30 to represent 30 days’ time and the result is added to the
invoiceDate value and used to set the dueDate value.
Converting between time zones
Flash Player 9 and later, Adobe AIR 1.0 and later
Date and time arithmetic comes in handy when you want to convert dates from one time zone to another. So does the
getTimezoneOffset() method, which returns the value in minutes by which the Date object’s time zone differs from
UTC. It returns a value in minutes because not all time zones are set to even-hour increments—some have half-hour
offsets from neighboring zones.
The following example uses the time zone offset to convert a date from local time to UTC. It does the conversion by
first calculating the time zone value in milliseconds and then adjusting the Date value by that amount:
// creates a Date in local time
var nextDay:Date = new Date("Mon May 1 2006 11:30:00 AM");
// converts the Date to UTC by adding or subtracting the time zone offset
var offsetMilliseconds:Number = nextDay.getTimezoneOffset() * 60 * 1000;
nextDay.setTime(nextDay.getTime() + offsetMilliseconds);
Last updated 3/21/2011
ACTIONSCRIPT 3.0 DEVELOPER’S GUIDE
Working with dates and times
Controlling time intervals
Flash Player 9 and later, Adobe AIR 1.0 and later
When you develop applications using Adobe Flash CS4 Professional, you have access to the timeline, which provides
a steady, frame-by-frame progression through your application. In pure ActionScript projects, however, you must rely
on other timing mechanisms.
Loops versus timers
Flash Player 9 and later, Adobe AIR 1.0 and later
In some programming languages, you must devise your own timing schemes using loop statements like for or
do..while.
Loop statements generally execute as fast as the local machine allows, which means that the application runs faster on
some machines and slower on others. If your application needs a consistent timing interval, you need to tie it to an
actual calendar or clock time. Many applications, such as games, animations, and real-time controllers, need regular,
time-driven ticking mechanisms that are consistent from machine to machine.
4
The ActionScript 3.0 Timer class provides a powerful solution. Using the ActionScript 3.0 event model, the Timer class
dispatches timer events whenever a specified time interval is reached.
The Timer class
Flash Player 9 and later, Adobe AIR 1.0 and later
The preferred way to handle timing functions in ActionScript 3.0 is to use the Timer class (flash.utils.Timer), which
can be used to dispatch events whenever an interval is reached.
To start a timer, you first create an instance of the Timer class, telling it how often to generate a timer event and how
many times to do so before stopping.
For example, the following code creates a Timer instance that dispatches an event every second and continues for 60
seconds:
var oneMinuteTimer:Timer = new Timer(1000, 60);
The Timer object dispatches a TimerEvent object each time the given interval is reached. A TimerEvent object’s event
timer (defined by the constant TimerEvent.TIMER). A TimerEvent object contains the same properties as a
type is
standard Event object.
If the Timer instance is set to a fixed number of intervals, it will also dispatch a timerComplete event (defined by the
constant
Here is a small sample application showing the Timer class in action:
TimerEvent.TIMER_COMPLETE) when it reaches the final interval.
public class ShortTimer extends Sprite
{
public function ShortTimer()
{
// creates a new five-second Timer
var minuteTimer:Timer = new Timer(1000, 5);
// designates listeners for the interval and completion events
minuteTimer.addEventListener(TimerEvent.TIMER, onTick);
minuteTimer.addEventListener(TimerEvent.TIMER_COMPLETE, onTimerComplete);
// starts the timer ticking
minuteTimer.start();
}
public function onTick(event:TimerEvent):void
{
// displays the tick count so far
// The target of this event is the Timer instance itself.
trace("tick " + event.target.currentCount);
}
public function onTimerComplete(event:TimerEvent):void
{
trace("Time's Up!");
}
}
}
5
When the ShortTimer class is created, it creates a Timer instance that will tick once per second for five seconds. Then
it adds two listeners to the timer: one that listens to each tick, and one that listens for the
timerComplete event.
Next, it starts the timer ticking, and from that point forward, the onTick() method executes at one-second intervals.
The onTick() method simply displays the current tick count. After five seconds have passed, the
onTimerComplete() method executes, telling you that the time is up.
When you run this sample, you should see the following lines appear in your console or trace window at the rate of
one line per second:
tick 1
tick 2
tick 3
tick 4
tick 5
Time's Up!
Last updated 3/21/2011
ACTIONSCRIPT 3.0 DEVELOPER’S GUIDE
Working with dates and times
Timing functions in the flash.utils package
Flash Player 9 and later, Adobe AIR 1.0 and later
ActionScript 3.0 contains a number of timing functions similar to those that were available in ActionScript 2.0. These
functions are provided as package-level functions in the flash.utils package, and they operate just as they did in
ActionScript 2.0.
FunctionDescription
clearInterval(id:uint):voidCancels a specified setInterval() call.
clearTimeout(id:uint):voidCancels a specified setTimeout() call.
Returns the number of milliseconds that have elapsed since Adobe® Flash® Player
or Adobe
® AIR™ was initialized.
Runs a function at a specified interval (in milliseconds).
Runs a specified function after a specified delay (in milliseconds).
These functions remain in ActionScript 3.0 for backward compatibility. Adobe does not recommend that you use them
in new ActionScript 3.0 applications. In general, it is easier and more efficient to use the Timer class in your
applications.
Date and time example: Simple analog clock
Flash Player 9 and later, Adobe AIR 1.0 and later
A simple analog clock example illustrates these two date and time concepts:
• Getting the current date and time and extracting values for the hours, minutes, and seconds
• Using a Timer to set the pace of an application
To get the application files for this sample, see www.adobe.com/go/learn_programmingAS3samples_flash. The
SimpleClock application files can be found in the folder Samples/SimpleClock. The application consists of the
following files:
FileDescription
SimpleClockApp.mxml
or
SimpleClockApp.fla
com/example/programmingas3/simpleclock/SimpleClock.asThe main application file.
com/example/programmingas3/simpleclock/AnalogClockFace.asDraws a round clock face and hour, minute, and seconds
The main application file in Flash (FLA) or Flex (MXML).
hands based on the time.
Last updated 3/21/2011
ACTIONSCRIPT 3.0 DEVELOPER’S GUIDE
Working with dates and times
Defining the SimpleClock class
Flash Player 9 and later, Adobe AIR 1.0 and later
The clock example is simple, but it’s a good idea to organize even simple applications well so you could easily expand
them in the future. To that end, the SimpleClock application uses the SimpleClock class to handle the startup and timekeeping tasks, and then uses another class named AnalogClockFace to actually display the time.
Here is the code that defines and initializes the SimpleClock class (note that in the Flash version, SimpleClock extends
the Sprite class instead):
public class SimpleClock extends UIComponent
{
/**
* The time display component.
*/
private var face:AnalogClockFace;
/**
* The Timer that acts like a heartbeat for the application.
*/
private var ticker:Timer;
7
The class has two important properties:
• The face property, which is an instance of the AnalogClockFace class
• The ticker property, which is an instance of the Timer class
The SimpleClock class uses a default constructor. The initClock() method takes care of the real setup work,
creating the clock face and starting the Timer instance ticking.
Creating the clock face
Flash Player 9 and later, Adobe AIR 1.0 and later
The next lines in the SimpleClock code create the clock face that is used to display the time:
/**
* Sets up a SimpleClock instance.
*/
public function initClock(faceSize:Number = 200)
{
// creates the clock face and adds it to the display list
face = new AnalogClockFace(Math.max(20, faceSize));
face.init();
addChild(face);
// draws the initial clock display
face.draw();
The size of the face can be passed in to the initClock() method. If no faceSize value is passed, a default size of 200
pixels is used.
Next, the application initializes the face and then adds it to the display list using the addChild() method inherited
from the DisplayObjectContainer class. Then it calls the
AnalogClockFace.draw() method to display the clock face
once, showing the current time.
Last updated 3/21/2011
ACTIONSCRIPT 3.0 DEVELOPER’S GUIDE
Working with dates and times
Starting the timer
Flash Player 9 and later, Adobe AIR 1.0 and later
After creating the clock face, the initClock() method sets up a timer:
// creates a Timer that fires an event once per second
ticker = new Timer(1000);
// designates the onTick() method to handle Timer events
ticker.addEventListener(TimerEvent.TIMER, onTick);
// starts the clock ticking
ticker.start();
First this method instantiates a Timer instance that will dispatch an event once per second (every 1000 milliseconds).
Since no second
indefinitely.
The SimpleClock.onTick() method will execute once per second when the timer event is received:
public function onTick(event:TimerEvent):void
{
// updates the clock display
face.draw();
}
repeatCount parameter is passed to the Timer() constructor, the Timer will keep repeating
8
The AnalogClockFace.draw() method simply draws the clock face and hands.
Displaying the current time
Flash Player 9 and later, Adobe AIR 1.0 and later
Most of the code in the AnalogClockFace class involves setting up the clock face’s display elements. When the
AnalogClockFace is initialized, it draws a circular outline, places a numeric text label at each hour mark, and then
creates three Shape objects, one each for the hour hand, the minute hand, and the second hand on the clock.
Once the SimpleClock application is running, it calls the AnalogClockFace.draw() method each second, as follows:
/**
* Called by the parent container when the display is being drawn.
*/
public override function draw():void
{
// stores the current date and time in an instance variable
currentTime = new Date();
showTime(currentTime);
}
This method saves the current time in a variable, so the time can’t change in the middle of drawing the clock hands.
Then it calls the
showTime() method to display the hands, as the following shows:
Last updated 3/21/2011
ACTIONSCRIPT 3.0 DEVELOPER’S GUIDE
Working with dates and times
/**
* Displays the given Date/Time in that good old analog clock style.
*/
public function showTime(time:Date):void
{
// gets the time values
var seconds:uint = time.getSeconds();
var minutes:uint = time.getMinutes();
var hours:uint = time.getHours();
// multiplies by 6 to get degrees
this.secondHand.rotation = 180 + (seconds * 6);
this.minuteHand.rotation = 180 + (minutes * 6);
// Multiply by 30 to get basic degrees, then
// add up to 29.5 degrees (59 * 0.5)
// to account for the minutes.
this.hourHand.rotation = 180 + (hours * 30) + (minutes * 0.5);
}
First, this method extracts the values for the hours, minutes, and seconds of the current time. Then it uses these values
to calculate the angle for each hand. Since the second hand makes a full rotation in 60 seconds, it rotates 6 degrees each
second (360/60). The minute hand rotates the same amount each minute.
9
The hour hand updates every minute, too, so it can show some progress as the minutes tick by. It rotates 30 degrees
each hour (360/12), but it also rotates half a degree each minute (30 degrees divided by 60 minutes).
Last updated 3/21/2011
Chapter 2: Working with strings
Flash Player 9 and later, Adobe AIR 1.0 and later
The String class contains methods that let you work with text strings. Strings are important in working with many
objects. The methods described here are useful for working with strings used in objects such as TextField, StaticText,
XML, ContextMenu, and FileReference objects.
Strings are sequences of characters. ActionScript 3.0 supports ASCII and Unicode characters.
More Help topics
String
RegExp
parseFloat()
parseInt()
10
Basics of strings
Flash Player 9 and later, Adobe AIR 1.0 and later
In programming parlance, a string is a text value—a sequence of letters, numbers, or other characters strung together
into a single value. For instance, this line of code creates a variable with the data type String and assigns a literal string
value to that variable:
var albumName:String = "Three for the money";
As this example shows, in ActionScript you can denote a string value by surrounding text with double or single
quotation marks. Here are several more examples of strings:
"Hello"
"555-7649"
"http://www.adobe.com/"
Any time you manipulate a piece of text in ActionScript, you are working with a string value. The ActionScript String
class is the data type you can use to work with text values. String instances are frequently used for properties, method
parameters, and so forth in many other ActionScript classes.
Important concepts and terms
The following reference list contains important terms related to strings that you will encounter:
ASCII A system for representing text characters and symbols in computer programs. The ASCII system supports the
26-letter English alphabet, plus a limited set of additional characters.
Character The smallest unit of text data (a single letter or symbol).
Concatenation Joining multiple string values together by adding one to the end of the other, creating a new string
value.
Last updated 3/21/2011
ACTIONSCRIPT 3.0 DEVELOPER’S GUIDE
Working with strings
Empty string A string that contains no text, white space, or other characters, written as "". An empty string value is
different from a String variable with a null value—a null String variable is a variable that does not have a String instance
assigned to it, whereas an empty string has an instance with a value that contains no characters.
String A textual value (sequence of characters).
String literal (or “literal string”) A string value written explicitly in code, written as a text value surrounded by double
quotation marks or single quotation marks.
Substring A string that is a portion of another string.
Unicode A standard system for representing text characters and symbols in computer programs. The Unicode system
allows for the use of any character in any writing system.
Creating strings
Flash Player 9 and later, Adobe AIR 1.0 and later
The String class is used to represent string (textual) data in ActionScript 3.0. ActionScript strings support both ASCII
and Unicode characters. The simplest way to create a string is to use a string literal. To declare a string literal, use
straight double quotation mark (
equivalent:
") or single quotation mark (') characters. For example, the following two strings are
11
var str1:String = "hello";
var str2:String = 'hello';
You can also declare a string by using the new operator, as follows:
var str1:String = new String("hello");
var str2:String = new String(str1);
var str3:String = new String(); // str3 == ""
The following two strings are equivalent:
var str1:String = "hello";
var str2:String = new String("hello");
To use single quotation marks (') within a string literal defined with single quotation mark (') delimiters, use the
backslash escape character (
quotation marks (
var str1:String = "That's \"A-OK\"";
var str2:String = 'That\'s "A-OK"';
") delimiters, use the backslash escape character (\). The following two strings are equivalent:
\). Similarly, to use double quotation marks (") within a string literal defined with double
You may choose to use single quotation marks or double quotation marks based on any single or double quotation
marks that exist in a string literal, as in the following:
var str1:String = "ActionScript <span class='heavy'>3.0</span>";
var str2:String = '<item id="155">banana</item>';
Keep in mind that ActionScript distinguishes between a straight single quotation mark (') and a left or right single
quotation mark (
' or ' ). The same is true for double quotation marks. Use straight quotation marks to delineate
string literals. When pasting text from another source into ActionScript, be sure to use the correct characters.
As the following table shows, you can use the backslash escape character (\) to define other characters in string literals:
Last updated 3/21/2011
ACTIONSCRIPT 3.0 DEVELOPER’S GUIDE
Working with strings
Escape sequenceCharacter
\bBackspace
\fForm feed
\nNewline
\rCarriage return
\tTab
12
\unnnnThe Unicode character with the character code specified by the hexadecimal number nnnn; for
\\xnnThe ASCII character with the character code specified by the hexadecimal number nn
\'Single quotation mark
\"Double quotation mark
\\Single backslash character
\u263a is the smiley character.
example,
The length property
Flash Player 9 and later, Adobe AIR 1.0 and later
Every string has a length property, which is equal to the number of characters in the string:
var str:String = "Adobe";
trace(str.length); // output: 5
An empty string and a null string both have a length of 0, as the following example shows:
var str1:String = new String();
trace(str1.length); // output: 0
Every character in a string has an index position in the string (an integer). The index position of the first character is
0. For example, in the following string, the character
"yellow"
You can examine individual characters in various positions in a string using the charAt() method and the
charCodeAt() method, as in this example:
var str:String = "hello world!";
for (var i:int = 0; i < str.length; i++)
{
trace(str.charAt(i), "-", str.charCodeAt(i));
}
Last updated 3/21/2011
y is in position 0 and the character w is in position 5:
ACTIONSCRIPT 3.0 DEVELOPER’S GUIDE
Working with strings
When you run this code, the following output is produced:
h - 104
e - 101
l - 108
l - 108
o - 111
- 32
w - 119
o - 111
r - 114
l - 108
d - 100
! - 33
You can also use character codes to define a string using the fromCharCode() method, as the following example
shows:
var myStr:String = String.fromCharCode(104,101,108,108,111,32,119,111,114,108,100,33);
// Sets myStr to "hello world!"
13
Comparing strings
Flash Player 9 and later, Adobe AIR 1.0 and later
You can use the following operators to compare strings: <, <=, !=, ==, =>, and >. These operators can be used with
conditional statements, such as
var str1:String = "Apple";
var str2:String = "apple";
if (str1 < str2)
{
trace("A < a, B < b, C < c, ...");
}
When using these operators with strings, ActionScript considers the character code value of each character in the
string, comparing characters from left to right, as in the following:
Additionally, the String class includes a concat() method, which can be used as follows:
var str1:String = "Bonjour";
var str2:String = "from";
var str3:String = "Paris";
var str4:String = str1.concat(" ", str2, " ", str3);
// str4 == "Bonjour from Paris"
If you use the + operator (or the += operator) with a String object and an object that is not a string, ActionScript
automatically converts the nonstring object to a String object in order to evaluate the expression, as shown in this
example:
Substrings are sequential characters within a string. For example, the string "abc" has the following substrings: "",
"a", "ab", "abc", "b", "bc", "c". You can use ActionScript methods to locate substrings of a string.
Patterns are defined in ActionScript by strings or by regular expressions. For example, the following regular expression
defines a specific pattern—the letters A, B, and C followed by a digit character (the forward slashes are regular
expression delimiters):
/ABC\d/
ActionScript includes methods for finding patterns in strings and for replacing found matches with replacement
substrings. These methods are described in the following sections.
Regular expressions can define intricate patterns. For more information, see “Using regular expressions” on page 76.
Finding a substring by character position
Flash Player 9 and later, Adobe AIR 1.0 and later
15
The substr() and substring() methods are similar. Both return a substring of a string. Both take two parameters.
In both methods, the first parameter is the position of the starting character in the given string. However, in the
substr() method, the second parameter is the length of the substring to return, and in the substring() method, the
second parameter is the position of the character at the end of the substring (which is not included in the returned
string). This example shows the difference between these two methods:
var str:String = "Hello from Paris, Texas!!!";
trace(str.substr(11,15)); // output: Paris, Texas!!!
trace(str.substring(11,15)); // output: Pari
The slice() method functions similarly to the substring() method. When given two non-negative integers as
parameters, it works exactly the same. However, the
slice() method can take negative integers as parameters, in
which case the character position is taken from the end of the string, as shown in the following example:
var str:String = "Hello from Paris, Texas!!!";
trace(str.slice(11,15)); // output: Pari
trace(str.slice(-3,-1)); // output: !!
trace(str.slice(-3,26)); // output: !!!
trace(str.slice(-3,str.length)); // output: !!!
trace(str.slice(-8,-3)); // output: Texas
You can combine non-negative and negative integers as the parameters of the slice() method.
Finding the character position of a matching substring
Flash Player 9 and later, Adobe AIR 1.0 and later
You can use the indexOf() and lastIndexOf() methods to locate matching substrings within a string, as the
following example shows:
var str:String = "The moon, the stars, the sea, the land";
trace(str.indexOf("the")); // output: 10
Notice that the indexOf() method is case-sensitive.
Last updated 3/21/2011
ACTIONSCRIPT 3.0 DEVELOPER’S GUIDE
Working with strings
You can specify a second parameter to indicate the index position in the string from which to start the search, as
follows:
var str:String = "The moon, the stars, the sea, the land"
trace(str.indexOf("the", 11)); // output: 21
The lastIndexOf() method finds the last occurrence of a substring in the string:
var str:String = "The moon, the stars, the sea, the land"
trace(str.lastIndexOf("the")); // output: 30
If you include a second parameter with the lastIndexOf() method, the search is conducted from that index position
in the string working backward (from right to left):
var str:String = "The moon, the stars, the sea, the land"
trace(str.lastIndexOf("the", 29)); // output: 21
Creating an array of substrings segmented by a delimiter
Flash Player 9 and later, Adobe AIR 1.0 and later
You can use the split() method to create an array of substrings, which is divided based on a delimiter. For example,
you can segment a comma-delimited or tab-delimited string into multiple strings.
16
The following example shows how to split an array into substrings with the ampersand (&) character as the delimiter:
var queryStr:String = "first=joe&last=cheng&title=manager&StartDate=3/6/65";
var params:Array = queryStr.split("&", 2); // params == ["first=joe","last=cheng"]
The second parameter of the split() method, which is optional, defines the maximum size of the array that is
returned.
You can also use a regular expression as the delimiter character:
var str:String = "Give me\t5."
var a:Array = str.split(/\s+/); // a == ["Give","me","5."]
For more information, see “Using regular expressions” on page 76 and the ActionScript 3.0 Reference for the Adobe
Flash Platform.
Finding patterns in strings and replacing substrings
Flash Player 9 and later, Adobe AIR 1.0 and later
The String class includes the following methods for working with patterns in strings:
• Use the match() and search() methods to locate substrings that match a pattern.
• Use the replace() method to find substrings that match a pattern and replace them with a specified substring.
These methods are described in the following sections.
You can use strings or regular expressions to define patterns used in these methods. For more information on regular
expressions, see
“Using regular expressions” on page 76.
Finding matching substrings
The search() method returns the index position of the first substring that matches a given pattern, as shown in this
example:
Last updated 3/21/2011
ACTIONSCRIPT 3.0 DEVELOPER’S GUIDE
Working with strings
var str:String = "The more the merrier.";
// (This search is case-sensitive.)
trace(str.search("the")); // output: 9
You can also use regular expressions to define the pattern to match, as this example shows:
var pattern:RegExp = /the/i;
var str:String = "The more the merrier.";
trace(str.search(pattern)); // 0
The output of the trace() method is 0, because the first character in the string is index position 0. The i flag is set in
the regular expression, so the search is not case-sensitive.
The search() method finds only one match and returns its starting index position, even if the g (global) flag is set in
the regular expression.
The following example shows a more intricate regular expression, one that matches a string in double quotation marks:
var pattern:RegExp = /"[^"]*"/;
var str:String = "The \"more\" the merrier.";
trace(str.search(pattern)); // output: 4
str = "The \"more the merrier.";
trace(str.search(pattern)); // output: -1
// (Indicates no match, since there is no closing double quotation mark.)
17
The match() method works similarly. It searches for a matching substring. However, when you use the global flag in
a regular expression pattern, as in the following example,
var str:String = "bob@example.com, omar@example.org";
var pattern:RegExp = /\w*@\w*\.[org|com]+/g;
var results:Array = str.match(pattern);
match() returns an array of matching substrings:
The results array is set to the following:
["bob@example.com","omar@example.org"]
For more information on regular expressions, see “Using regular expressions” on page 76.
Replacing matched substrings
You can use the replace() method to search for a specified pattern in a string and replace matches with the specified
replacement string, as the following example shows:
var str:String = "She sells seashells by the seashore.";
var pattern:RegExp = /sh/gi;
trace(str.replace(pattern, "sch")); //sche sells seaschells by the seaschore.
Note that in this example, the matched strings are not case-sensitive because the i (ignoreCase) flag is set in the
regular expression, and multiple matches are replaced because the
g (global) flag is set. For more information, see
“Using regular expressions” on page 76.
You can include the following $ replacement codes in the replacement string. The replacement text shown in the
following table is inserted in place of the
$ replacement code:
Last updated 3/21/2011
Loading...
+ 1080 hidden pages
You need points to download manuals.
1 point = 1 manual.
You can buy points or you can get point for every manual you upload.