Name

String.substring( ) Method — extract a substring from a string based on positive character positions

Availability

Flash 5

Synopsis

string.substring(startIndex, endIndex)

Arguments

startIndex

The positive integer position of the first character to extract from string. If negative, 0 is used.

endIndex

The positive integer position of the character after the last character to extract from string. Defaults to string .length if omitted. If negative, 0 is used.

Returns

A substring of string, starting at startIndex and ending at endIndex- 1, where both startIndex and endIndex are zero-relative.

Description

The substring( ) method is one of three methods that can be used to extract a substring from a string (the others being slice( ) and substr( ) ). The substring( ) function is identical to slice( ) except that it does not allow for negative startIndex and endIndex values, and it automatically reorders the two indexes if endIndex is less than startIndex.

Usage

Note that substring( ) does not modify string; it returns a completely new string.

Example

// Extract names from a string
var fullName = "Steven Sid Mumby";
middleName = fullName.substring(7, 10);   // Assigns "Sid" to middleName
middleName = fullName.substring(10, 7);   // Assigns "Sid" to middleName
                                          // (indexes are swapped automatically)
firstName  = fullName.substring(0, 6);    // Assigns "Steven" to firstName
lastName   = fullName.substring(11);      // Assigns "Mumby" to lastName

The following example is a reusable function to search for and replace ...

Get ActionScript: The Definitive Guide 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.