O'Reilly logo

ActionScript 3.0 Cookbook by Joey Lott, Darron Schall, Keith Peters

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

Extracting a Substring

Problem

You want to extract a substring from a string.

Solution

Use the substring(), substr(), or slice() methods.

Discussion

The substring(), substr(), and slice() methods all return the value of a substring without affecting the original string. The only difference between the three methods is in the parameters they accept.

The substr() method takes up to two parameters.

startIndex

The position of the first character of the substring. The value can be negative, in which case the index is calculated from the end of the string, where -1 is the last character, -2 is the second-to-last character, and so on.

length

The number of characters in the substring to extract. If this parameter is omitted, all the characters from the start index to the end are used.

var example:String = "Bunnies";
trace( example.substr( 0 ) );      // Displays: Bunnies
trace( example.substr( 0, 3 ) );   // Displays: Bun
trace( example.substr( 3, 3 ) );   // Displays: nie
trace( example.substr( -1 ) );     // Displays: s
trace( example.substr( -2, 5 ) );  // Displays: es

The substring() and slice() method both take the same parameters.

startIndex

The position of the first character of the substring to extract.

endIndex

The position of one character after the last character in the substring to extract. That is, the substring will include from start index up to, but not including, the character at endIndex. If this parameter is omitted, all the characters from the start index to the end of the string are used.

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