Recipe 12.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 the
start index to the end are used.
var example:String = "Bunnies";
trace( example.substr( 0 ) ); // Displays: Bunnies
trace( example.substr( 0, 3 ) ); // Displays: Bun
trace( example.substr( 3, 3 ) ); // Displays: nie
trace( example.substr( -1 ) ); // Displays: s
trace( example.substr( -2, 5 ) ); // Displays: es
The substring( ) and slice( )
method both 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. That is, the substring will
include from start index up to, but not including, the character at
endIndex. If this parameter is omitted, all the characters
from the start index to the end of the string are used.
The substring( ) and slice( )
methods differ in that substring( ) accepts positive index
values only; it interprets negative values as 0. Also, if
endIndex is less than startIndex,
the substring( ) method automatically reverses them before
executing, always using the smaller of the two parameters as the
starting index. The slice( ) method, on the other hand,
accepts negative values for both startIndex and
endIndex; it interprets negative values as counting
back from the end of the string, where -1 is the last character in
the string. The slice( ) method returns an empty string if
you specify an endIndex that is less than
startIndex.
var example:String = "Rabbits";
// Both of these output the entire string, beginning at index 0 and
// going to the last index (the value of which is example.length - 1).
trace( example.substring( 0 ) ); // Displays: Rabbits
trace( example.slice( 0 ) ); // Displays: Rabbits
// The substring( ) method outputs nothing because it converts the negative
// indices to 0. The slice( ) method outputs "it", which is the substring from
// the third-to-last character (index -3) to next-to-last character (index -1).
trace( example.substring( -3, -1 ) ); // Displays nothing (an empty string)
trace( example.slice( -3, -1 ) ); // Displays: it
// Both of these output the substring "ab".
trace( example.substring( 1, 3 ) ); // Displays: ab
trace( example.slice( 1, 3 ) ); // Displays: ab
// The substring( ) method outputs the substring "ab" because it reverses the
// order of the parameters automatically. The slice( ) method outputs nothing
// because the slice( ) method does not reverse the order of the parameters.
trace( example.substring( 3, 1 ) ); // Displays: ab
trace( example.slice( 3, 1 ) ); // Displays nothing (an empty string)
You commonly use the substring extraction
methods in conjunction with the indexOf( ) and
lastIndexOf( ) methods. You can use indexOf( ) and
lastIndexOf( ) methods to search for the substring within a
string, and then use the substring extraction methods to get the
substrings.
This example extracts a file's extension and its
filename (without the extension), presumed to be separated from
each other by a period:
var filename:String = "document.jpg";
// Find the location of the period.
var extensionIndex:Number = filename.lastIndexOf( '.' );
// The extension-less filename ("mydocument") is everything before the period.
var extensionless:String = filename.substr( 0, extensionIndex );
trace( "The filename is " + extensionless );
// The extension ("jpg") is everything after the period.
var extension:String = filename.substr( extensionIndex + 1, filename.length );
trace( "The file extension is " + extension );
You can also use the split( ) method,
assuming there is only one period in the filename:
var filename:String = "document.jpg";
// Split the string wherever the period occurs.
var nameParts:Array = filename.split(".");
// The first element is "document" (everything before the first period).
var extensionless:String = nameParts[0];
trace ("The filename is " + extensionless);
// The next element is "jpg" (anything after the first
// period and before the next one).
var extension:String = nameParts[1];
trace ("The file extension is " + extension);
Compare and contrast the two preceding examples.
What if the filename doesn't contain a period, e.g.,
document? (Hint: The first example produces invalid
results.) What if the filename contains more than one period, such
as ascb_fig8.1.bmp? (Hint: The second example produces
invalid results.)
Here is a general solution:
// This method returns everything before the last period, if any.
private function removeExtension( filename:String ):String {
// Find the location of the period.
var extensionIndex:Number = filename.lastIndexOf( '.' );
if ( extensionIndex == -1 ) {
// Oops, there is no period. Just return the filename.
return filename;
} else {
return filename.substr( 0, extensionIndex );
}
}
// This method returns everything after the last period, if any.
private function extractExtension( filename:String ):String {
// Find the location of the period.
var extensionIndex:Number = filename.lastIndexOf( '.' );
if ( extensionIndex == -1 ) {
// Oops, there is no period, so return the empty string.
return "";
} else {
return filename.substr( extensionIndex + 1, filename.length );
}
}
Here's example usage:
trace( removeExtension( "document.jpg" ) ); // Displays: document
trace( removeExtension( "document" ) ); // Displays: document
trace( removeExtension( "document.1.jpg" ) ); // Displays: document.1
trace( extractExtension( "document.jpg" ) ); // Displays: .jpg
trace( extractExtension( "document" ) ); // Displays nothing
trace( extractExtension( "document.1.jpg" ) ); // Displays: .jpg
See Also
Recipe
12.6
|