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

Searching for a Substring

Problem

You want to find a string value inside of a string.

Solution

Use the indexOf() or lastIndexOf() methods from the String class.

Discussion

You can use the indexOf() and lastIndexOf() methods to determine whether a string contains a specified substring value. Each method returns the starting index of the substring found. The indexOf() method searches from left to right, whereas the lastIndexOf() methods searches from right to left in the string. If the substring is not found, the value -1 is returned.

The indexOf() method takes two parameters:

substring

The substring value for which you want to search.

startIndex

The optional zero-based starting position from which to search within the string. Zero-based means the first character in the string is at position 0, not 1. If omitted, the method begins the search from the beginning of the string (at index 0).

If you want to test whether a string contains another string, you can use the indexOf() method with only one parameter. For example:

var example:String = "This string contains the word cool twice. Very cool.";

// Get the index of the first occurrence of the substring "cool" within example. 
var index:int = example.indexOf( "cool" );

// If the indexOf() method returns –1, no occurrences of "cool" were found.
if ( index != -1 ) {
  // Displays: "String contains word cool at index 30" because the first
  // occurrence of the substring appears starting at index 30 within example. trace( "String contains word cool at ...

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