JavaScript String substr() Method

The substr() method returns the characters in a string beginning at the specified location through the specified number of characters.

Syntax

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:

Example
Begin the extraction at position 3, and extract the rest of the string:

Example

Extract only the first character:

Example
Extract only the last character:

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.

You Might Interested In

Leave a Reply

Enclose a code block like: <pre><code>Your Code Snippet</code></pre>.