Manipulating Strings

String manipulation includes creating new strings, joining strings, and much more. In this section, we'll start with the easy tasks and work our way up.

Joining Strings

Joining strings is as simple as putting a plus operator (+) between two string literals. Here's an example:

 "This is " + "a string literal" // the interpreter translates this as "This is a string literal" 

Notice the space after "is" in the preceding example. This space is necessary in strings; otherwise, the string would appear like this: "This isa string literal". Alternatively, we could use a space string to make the code look cleaner, as shown here:

 "This is" + " " + "a string literal" // the interpreter translates this as "This is a string literal" 

Note that the space string is not equal to the empty string we discussed earlier:

 if (" " != '') {        trace ("A space string is not equal to an empty string") } // output: A space string is not equal to an empty string 

You can also add strings by setting them to variables:

 var fName_str:String = "David"; var lName_str:String = "Vogeleer"; var space_str:String = " "; trace (fName_str + space_str + lName_str); // output: David Vogeleer 

Here, all we did was set each string to a variable and then add the variables.

Another way to add strings with variables is to set the same variable to an additional string with an assignment operator. Here's an example:

 var myName_str:String = "David "; myName_str += "Vogeleer"; trace (myName_str); // output: David Vogeleer 

Notice that we added the string to the variable, but you cannot add the variable from within a string. The following example shows this:

 var fName_str:String = "David "; var lName_str:String = "Vogeleer"; var fullName_str:String = "fName_str + lName_str"; trace (fullName_str); // output: fName_str + lName_str 

So keep in mind that you cannot use variables from within a string.

You can, however, create a new string by adding a string to a variable that contains a string, as shown here:

 var fName_str:String = "David "; var fullName_str:String = fName_str + "Vogeleer"; trace (fullName_str); // output: David Vogeleer 

The concat Function

Using dot syntax, the concat function acts similarly to the assignment variable (+=) we looked at earlier. Simply attach it to a string with another string in the parenthesis:

 var name_str:String = "David ".concat("Vogeleer"); trace (name_str); // output: David Vogeleer 

And, of course, you can attach the concat function to a variable:

 var fName_str:String = "David "; var fullName_str:String = fName_str.concat("Vogeleer"); trace (fullName_str); // output: David Vogeleer 

Now let's put a variable in the parentheses instead of a string literal:

 var fName_str:String = "David "; var lName_str:String = "Vogeleer"; var fullName_str:String = fName_str.concat(lName_str); trace (fullName_str); // output: David Vogeleer 

This technique can even handle multiple expressions:

 var myString_str:String = "This is ".concat("a"+" ".concat("string " + "literal")); trace (myString_str); // output: This is a string literal 

Not only can you use multiple joining expressions, but you can also embed concat functions within concat functions.

You can use the concat() method in place of the plus sign (+) in order to add strings together, but it is not necessary. As you can see in the previous examples, even though the end result is the same, using the plus sign to add strings reads better when you are looking over your code.

Indexing Characters in Strings

Characters inside of strings can be indexed, stored, and displayed. Each character in a string has a specific index, starting with the first character at the index zero (0). The indexing of strings always starts with 0 instead of 1 in Flash; therefore, the second character has an index of 1 and the third character has an index of 2, and so on (see Figure 9.1).

Figure 9.1. Indexing strings start with index 0 for the first character.

The charAt Method

You can use the charAt method with strings to see characters at a defined index. Just attach the method to a string and place a number in the parentheses that represents the index you want to grab. Here's an example:

 trace("David".charAt(2)); // output: v 

This function can also be attached to a variable holding a string:

 var name_str:String = "David"; trace (name_str.charAt(2)); // output: v 

What's more, you can use a variable in place of the number in the parentheses:

 var place:Number = 2; var name_str:String = "David"; trace (name_str.charAt(place)); // output: v 

The length Property

The length property provides a way to determine the number of characters in a given string. Simply attach it to a string, and it will return a numeric value. Here's an example:

 trace ("Unleashed".length); // output: 9 


The index of the last character in a string will always be string.length minus one.

Of course, this property can also be attached to a variable holding a string, as shown here:

 var myTitle_str:String= "Unleashed"; trace (myTitle_str.length); // output: 9 

Even though you might not consider a space to be a character, ActionScript does:

 var myTitle_str:String = "Flash Unleashed"; trace (myTitle_str.length); // output: 15 

In this example, the output is 15 instead of 14 because the space is counted as a character.

Using the length property combined with the charAt method, we can identify every character in a word based on a defined function (more on functions in Chapter 12). Here's an example:

 //first create the function list = function (myString:String):Void {    //use a loop statement to cycle through    //all the characters in the string    for(var i:Number = 0; i < myString.length; i++){          trace (myString.charAt(i));    } } //create our string var myTitle_str:String = "Unleashed"; //run the function on our string list(myTitle_str); // output: U //         n //         l //         e //         a //         s //         h //         e //         d 

The indexOf Method

The indexOf method takes a given character, looks for the first instance of it in a string, and returns that character's index. As before, you can attach it directly to a string or a variable holding a string. Place the character you are looking for in the parentheses as a string literal, like this:

 //attach the function directly to a string trace ("Flash".indexOf("a")); // now create a variable and attach the function to the variable var myTitle_str:String = "Unleashed"; trace (myTitle_str.indexOf("e")); // output: 2 //         3 

In the second part of the preceding example, the indexOf method found the first index of e, but let's say we now want to find the next one. To do this, we just place a starting index in the function after the character we are looking for and separate them with a comma:

 var myTitle_str:String = "Unleashed"; trace (myTitle_str.indexOf("e",4)); // output: 7 

In this case, we put in the index of the character following the first e and the indexOf method found the next one with no problem.

You can also look for certain strings of characters with the indexOf method. Just place the string in quotes as you would a single character. The indexOf method will return the first index of the first character in the string you are looking for:

 var myTitle_str:String = "Unleashed"; trace (myTitle_str.indexOf("she")); // output: 5 

The Output panel displays the index of the first character in the string you're looking for (in this case, s).

Here's another nice feature of the indexOf method: If it does not find the character or characters in the string, it will return -1 in the Output window when you trace it:

 var myTitle_str:String = "Unleashed"; trace (myTitle_str.indexOf("o")); // output: -1 

Let's take a look at what happens when we look for the letter u in the same string:

 var myTitle_str:String = "Unleashed"; trace (myTitle_str.indexOf("u")); // output: -1 

The indexOf method could not find u in this case because Flash reads upper- and lowercase letters as completely different characters.

This can be useful when you're using forms in Flash. For example, let's say your company is willing to pay for in-state shipping to its customers, but if the recipient is outside the state, he or she must pay the shipping. Therefore, when users enter another state in the shipping form, they are greeted with a message reminding them to include shipping costs (otherwise, a thank-you message appears):

 //first create the variables var homeState_str:String = "VA"; var thankYou_str:String = "Thank you for your order"; var reminder_str:String = "Please remember to include shipping"; //now create the if statement if (enteredState.indexOf(homeState_str) == -1) {       message = reminder_str; } else {       message = thankYou_str; } 

This code determines whether the variable homeState_str is in enteredState and sends the appropriate message.

The lastIndexOf Method

Like the indexOf method, the lastIndexOf method searches a string for a character or group of characters. However, unlike the indexOf method, which starts at the beginning of the string and moves toward the end, the lastIndexOf method starts at the end and works toward the beginning.

Also, this method works the same as the indexOf method in that you simply attach it to a string or variable holding a string and place the desired character or characters in parentheses, followed by a comma with a starting index. If no starting index is defined, the starting index automatically becomes the last character in the string. Here's an example:

 var myTitle_str:String = "Unleashed"; trace (myTitle_str.lastIndexOf("e")); // output: 7 

Although this method may not seem like much, consider that the following code is what it would take to do the same thing without the built-in lastIndexOf method:

 theLastIndexOf=function(myString:String,searchFor:String){       for (var i:Number = 0; i < myString.length; i++){             if (myString.charAt(i) == searchFor) {                   found = i;             }       }       trace (found); } var myTitle_str:String = "Unleashed"; theLastIndexOf(myTitle_str,"e"); // output: 7 

The substring Method

Many times, it is necessary to pull more than one character from a string. Flash has a few built-in methods for this task. One of them is the substring method.

The substring method attaches to strings and variables like other methods. However, in the parentheses, you put the starting and ending index, separated by a comma. Here's an example:

 trace("Unleashed".substring(2,7)) // output: leash 

Now let's attach it to a variable and leave out the ending index:

 var myTitle_str:String = "Unleashed"; trace (myTitle_str.substring(2)); // output: leashed 

As you can see, without an ending index, the substring method grabs all the characters from the starting index onward.

So far we have put in numbers representing the starting and ending indexes. Now let's use a variable instead of a number. This will make the function more dynamic. For example, let's say you would like to pull the ZIP Code out of the last line of an address:

 var line3_str:String = "Richmond, VA 23866"; var finalSpace:Number = line3_str.lastIndexOf(" "); var zip_str:String = line3_str.substring(finalSpace+1); trace (zip_str); // output: 23866 

This takes the last space in the third line and makes it the starting point. It then grabs everything after that, which in this case is the ZIP Code.

And, if by mistake, you place the ending index first and the starting index second, the interpreter will switch them for you:

 var myTitle_str:String = "Unleashed"; trace (myTitle_str.substring(7,2)); // output: leash 

Even though the numbers were reversed, the interpreter still retrieves the correct information.

The substr Method

The substr method acts similarly to the substring method. However, in place of an ending index, you put the desired number of characters to be returned. The substr method still uses a starting index like the substring method. Here's an example:

 var myTitle_str:String = "Unleashed"; trace (myTitle_str.substr(2,5)); // output: leash 

If you have a starting index but not a designated number of characters to pull, the substr method will begin at the starting point and pull all the following characters:

 var myTitle_str:String = "Unleashed"; trace (myTitle_str.substr(2)); // output: leashed 

You can also place a negative number in the starting index, and the substr method will start counting from the end toward the beginning using the specified number of spaces:

 var myTitle_str:String = "Unleashed"; trace (myTitle_str.substr(-4,2)); // output: sh 

The slice Method

The slice method acts similarly to the substring method, except you can use negative numbers in the starting and ending indexes, as shown here:

 var myTitle_str:String = "Unleashed"; trace (myTitle_str.slice(-7,-2)); // output: leash 

The split Method

The split method is a unique method when it comes to manipulating strings. It divides a string into separate strings that can be stored in an array (more on arrays in Chapter 10, "Arrays").

Attach the split method to a string or variable and in the parentheses place the delimiting character. Here's an example:

 var myTitle_str:String = "Unleashed"; trace (myTitle_str.split("e")); // output: Unl,ash,d 

The preceding example separates the original string based on the letter e. This is very powerful because you can take apart a sentence and store each individual word as its own variable or within an array as elements. Let's take a look:

 //first, create a variable holding the string var myTitle_str:String = "Flash 8 Unleashed"; // then set an array equal to the string with the function attached var myArray_array:Array = myTitle_str.split(" "); //display the entire array trace (myArray_array); //display just the first element in the array trace (myArray_array[0]); // output: Flash,8,Unleashed //         Flash 

Now you can see some of the capabilities this method has. You can sort, store, and send all this data in a nice, clean format thanks to the split method.

The toLowerCase Method

Earlier, we ran into a problem when trying to find a lowercase u in the word Unleashed because Flash does not treat lowercase characters the same as uppercase characters. This problem can be overcome with either the toLowerCase method or the toUpperCase method. Both work the same, except one converts characters to lowercase and the other to uppercase.

Let's go over toLowerCase first. When you want to find a letter in lowercase format in a string with uppercase letters, you must first convert all the uppercase letters to lowercase so that Flash will be able to find the lowercase version of the letter you are looking for. This can be done on an individual basis with a lot of tedious coding, or you can simply attach the toLowerCase method directly to the string. Here's an example:

 var myTitle_str:String = "Unleashed"; myTitle_str = myTitle_str.toLowerCase(); trace (myTitle_str); // output: unleashed 

In this case, we converted the uppercase U to a lowercase u. Now we can run the indexOf method as before and view the results:

 var myTitle_str:String = "Unleashed"; myTitle_str = myTitle_str.toLowerCase(); trace (myTitle_str.indexOf("u")); // output: 0 

The toUpperCase Method

The toUpperCase method is identical to the toLowerCase method, except instead of lowercasing a value in a string, it uppercases it. Attach this method as you would any other method with nothing in the parentheses:

 var myTitle_str:String = "Unleashed"; myTitle_str = myTitle_str.toUpperCase(); trace (myTitle_str); // output: UNLEASHED 

Like the toLowerCase method, the toUpperCase method affects the entire string.

The charCodeAt Method

We've talked about how Flash reads upper- and lowercase letters as different letters. This is because Flash doesn't see them as letters at all but rather as code points. The String object has two built-in methods for dealing with code points: the charCodeAt method and the fromCharCode method.

The first method, charCodeAt, takes characters at defined indexes of strings and returns the code point value in a numeric form. Attach this method as you would any other, and in the parentheses put the index of the character you're interested in. Here's an example:

 var myTitle_str:String = "Unleashed"; trace (myTitle_str.charCodeAt(2)); // output: 108 (the code point for the letter "l") 

The following code goes through any string and displays each character's code point in the Output window:

 //create the function listCodePoints = function (myString:String):Void{ //set the loop statement to run through each character       for(var i:Number=0; i < myString.length; i++){       //trace each character's code point             trace (myString.charCodeAt(i));       } } //create the variable to hold the string var myTitle_str:String = "Unleashed"; //run the function listCodePoints(myTitle_str); // output: 85 //         110 //         108 //         101 //         97 //         115 //         104 //         101 //         100 

Putting a negative value in the index place will always return the value NaN (Not a Number, covered later in this chapter in the "NaN" section):

 var myTitle_str:String = "Unleashed"; trace (myTitle_str.charCodeAt(-2)); // output: NaN 

The fromCharCode Method

Unlike the charCodeAt method, the fromCharCode method allows you to put code points in parentheses, and it translates them back to their string characters. Attach this method to a String identifier and put the code points you would like to see in parentheses, separated by commas:

 //create the variable to hold our string var myTitle_str:String ; myTitle_str = String.fromCharCode(85,110,108,101,97,115,104,101,100); trace (myTitle_str); // output: Unleashed 


The fromCharCode method must be attached to a String identifier when it is run because it is a static method; otherwise, it will return Undefined.

Unicode-Style Strings

Another way to create a string is by using Unicode-style escape sequences. Because Flash does not completely support the Unicode style, it emulates this style instead. The basic form of a Unicode escape sequence starts with a backslash character, then a lowercase u, followed by a four-digit number:

 var myTitle_str:String = "\u0055\u006e\u006c\u0065\u0061\u0073\u0068\u0065\u0064" trace (myTitle_str); // output: Unleashed 

Now you can type data in Unicode format into strings. The only real reason you would want to do this is to get those characters you can't simply type from the keyboard, such as the copyright symbol (©), which in Unicode is \u00A9.

You can also type Unicode in shorthand format by replacing the \u00 with \x, as shown here:

 trace ("0068"); trace ("\x68"); // output: h //         h 

That ends the string data type section. Up next is the other most popular data type in Flash.

Macromedia Flash Professional 8 Unleashed
Macromedia Flash Professional 8 Unleashed
ISBN: 0672327619
EAN: 2147483647
Year: 2005
Pages: 319 © 2008-2017.
If you may any questions please contact us: