9.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
startIndexto the end are used:myString = "Bunnies"; trace(myString.substr(0)); // Displays: Bunnies trace(myString.substr(0, 3)); // Displays: Bun trace(myString.substr(3, 3)); // Displays: nie trace(myString.substr(-1)); // Displays: s trace(myString.substr(-2, 5)); // Displays: es
The substring( ) and slice(
) methods
each
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. If this parameter is omitted, all the characters from the
startIndexto the end are used.
The substring( ) and slice(
) methods differ in that substring( ) accepts positive index values only; it interprets negative values ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access