substr()
returns a substring and accepts
either one or two arguments.
The first argument is the starting position. The second argument tells where to stop in term of the number of characters to return. If the second argument is omitted, it is default to the ending of the string.
substr()
does not alter the value of the string itself.
substr() |
Yes | Yes | Yes | Yes | Yes |
stringObject.substr(start, length);
Parameter | Description |
---|---|
start | Required.where to start. First character is at index 0 |
length | Optional. The number of characters to extract. Default to the string length |
Return the sub string.
If length is 0 or negative, an empty string is returned.
var stringValue = "hello world";
console.log(stringValue.substr(3)); //"lo world"
console.log(stringValue.substr(3, 7)); //"lo worl"
The code above generates the following result.
A negative first argument does the sub string from the end. A negative second number is converted to 0.
var stringValue = "hello world";
console.log(stringValue.substr(-3)); //"rld"
console.log(stringValue.substr(3, -4)); //"" (empty string)
The code above generates the following result.