The substr() method returns the characters in a string beginning at the specified location through the specified number of characters.
Syntax
1 | str.substr(start[, length]) |
Parameters
start
Required. The position where to start the extraction. First character is at index 0 If a negative number is given, it is treated as strLength+start where strLength = to the length of the string (for example, if start is -3 it is treated as strLength-3.)
length
Optional. The number of characters to extract. If omitted, it extracts the rest of the string.
Output
A new String, containing the extracted part of the text. If length is 0 or negative, an empty string is returned.
Example
Extract parts of a string:
1 2 3 4 5 | var str = "Fellow tuts!"; var output = str.substr(1, 4); The output will be: ello |
Example
Begin the extraction at position 3, and extract the rest of the string:
1 2 3 4 | var str = "fellow tuts!"; var output = str.substr(2) The output will be: low tuts! |
Example
Extract only the first character:
1 2 3 4 | var str = "fellow world!"; var output = str.substr(0, 1) The output will be: F |
Example
Extract only the last character:
1 2 3 4 | var str = "Fellow tuts!"; var output = str.substr(10, 2) The output will be: s! |
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 .
If length is 0 or negative, substr returns an empty string.
If length is omitted, substr extracts characters to the end of the string.