Core JavaScript 1.5 Reference:Global Objects:String:substr
From MDC
Contents |
[edit] Summary
Returns the characters in a string beginning at the specified location through the specified number of characters.
| Method of String | |
| Implemented in: | JavaScript 1.0, JScript 3 |
| ECMA Version: | None, although ECMA-262 ed. 3 has a non-normative section suggesting uniform semantics for substr |
[edit] Syntax
var sub = string.substr(start[, length]);
[edit] Parameters
-
start - Location at which to begin extracting characters (an integer between 0 and one less than the length of the string).
-
length - The number of characters to extract.
[edit] Description
start is a character index. The index of the first character is 0, and the index of the last character is 1 less than the length of the string. substr begins extracting characters at start and collects length characters (unless it reaches the end of the string first, in which case it will return fewer).
If start is positive and is greater than or equal to the length of the string, substr returns an empty string.
If start is negative, substr uses it as a character index from the end of the string. If start is negative and abs(start) is larger than the length of the string, substr uses 0 as the start index. Note: the described handling of negative values of the start argument is not supported by Microsoft JScript [1].
If length is 0 or negative, substr returns an empty string. If length is omitted, start extracts characters to the end of the string.
[edit] Examples
[edit] Example: Using substr
Consider the following script:
// assumes a print function is defined
var str = "abcdefghij";
print("(1,2): " + str.substr(1,2));
print("(-2,2): " + str.substr(-2,2));
print("(1): " + str.substr(1));
print("(-20, 2): " + str.substr(-20,2));
print("(20, 2): " + str.substr(20,2));
This script displays:
(1,2): bc (-2,2): ij (1): bcdefghij (-20, 2): ab (20, 2):