Table of Contents

String.substring( ) Method Flash 5

extract a substring from a string, based on positive character positions
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( ) method 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

Example 18-4 is a reusable function to search for and replace all occurrences of a substring within a string.

Example 18-4. A search-and-replace function
function replace (origStr, searchStr, replaceStr) {
  var tempStr = "";
  var startIndex = 0;
  if (searchStr =  = "") {
    return origStr;
  }
   
  if (origStr.indexOf(searchStr) != -1) {
    while ((searchIndex = origStr.indexOf(searchStr, startIndex)) != -1) {
      tempStr += origStr.substring(startIndex, searchIndex);
      tempStr += replaceStr;
      startIndex = searchIndex + searchStr.length;
    }
    return tempStr + origStr.substring(startIndex);
  } else {
    return origStr;
  }
}
   
msg = "three times three is four";
trace(replace(msg, "three", "two"));  // Displays: "two times two is four"

See Also

String.slice( ), String.substr( ); "Combining String Examination with Substring Extraction," and "The substr( ) function," in Chapter 4


Table of Contents