slice (String.slice method)

public slice(start:Number, end:Number) : String

Returns a string that includes the start character and all characters up to, but not including, the end character. The original String object is not modified. If the end parameter is not specified, the end of the substring is the end of the string. If the character indexed by start is the same as or to the right of the character indexed by end, the method returns an empty string.

Availability: ActionScript 1.0; Flash Player 5

Parameters

start:Number - The zero-based index of the starting point for the slice. If start is a negative number, the starting point is determined from the end of the string, where -1 is the last character.

end:Number - An integer that is one greater than the index of the ending point for the slice. The character indexed by the end parameter is not included in the extracted string. If this parameter is omitted, String.length is used. If end is a negative number, the ending point is determined by counting back from the end of the string, where -1 is the last character.

Returns

String - A substring of the specified string.

Example

The following example creates a variable, my_str, assigns it a String value, and then calls the slice() method using a variety of values for both the start and end parameters. Each call to slice() is wrapped in a trace() statement that displays the output in the Output panel.

// Index values for the string literal
// positive index: 0 1 2 3 4
// string: L o r e m
// negative index: -5 -4 -3 -2 -1

var my_str:String = "Lorem";

// slice the first character
trace("slice(0,1): "+my_str.slice(0, 1)); // output: slice(0,1): L
trace("slice(-5,1): "+my_str.slice(-5, 1)); // output: slice(-5,1): L

// slice the middle three characters
trace("slice(1,4): "+my_str.slice(1, 4)); // slice(1,4): ore
trace("slice(1,-1): "+my_str.slice(1, -1)); // slice(1,-1): ore

// slices that return empty strings because start is not to the left of end
trace("slice(1,1): "+my_str.slice(1, 1)); // slice(1,1):
trace("slice(3,2): "+my_str.slice(3, 2)); // slice(3,2):
trace("slice(-2,2): "+my_str.slice(-2, 2)); // slice(-2,2):

// slices that omit the end parameter use String.length, which equals 5
trace("slice(0): "+my_str.slice(0)); // slice(0): Lorem
trace("slice(3): "+my_str.slice(3)); // slice(3): em

For another example, see the Flash Samples page at www.adobe.com/go/learn_fl_samples. Download and decompress the Samples zip file and go to the ActionScript2.0\Strings folder to access the Strings.fla file.

See also

substr (String.substr method), substring (String.substring method)


Flash CS3