9.5. 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 startIndex to the end are used:

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

The substring( ) and slice( ) methods each 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. If this parameter is omitted, all the characters from the startIndex to the end are used.

The substring( ) and slice( ) methods differ in that substring( ) accepts positive index values only; it interprets negative values ...

Get Actionscript Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.