About strings and the String class 467
Returning substrings
The substr() and substring() methods of the String class are similar. Both return a
substring of a string and 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:
To find a substring by character position:
1. Create a new Flash document and save it as substring.fla.
2. Add the following ActionScript to Frame 1 of the main Timeline:
var myStr:String = "Hello from Paris, Texas!!!";
trace(myStr.substr(11,15)); // Paris, Texas!!!
trace(myStr.substring(11,15)); // Pari
The first method, substr(), returns a string 15 characters long starting from the eleventh
character. The second method,
substring(), returns a string four characters long by
grabbing all characters between the eleventh and fifteenth index.
3. Add the following ActionScript below the code added in the preceding step:
trace(myStr.slice(11, 15)); // Pari
trace(myStr.slice(-3, -1)); // !!
trace(myStr.slice(-3, 26)); // !!!
trace(myStr.slice(-3, myStr.length)); // !!!
trace(myStr.slice(-8, -3)); // Texas
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.
4. Select Control > Test Movie to test the Flash document.
You can use the
indexOf() and lastIndexOf() methods to locate matching substrings
within a string, as shown in the following example.
NOTE
You can combine non-negative and negative integers as the parameters of the
slice() method.