Javascript Reference - JavaScript String substr() Method








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.

Browser Support

substr() Yes Yes Yes Yes Yes




Syntax

stringObject.substr(start, length);

Parameter Values

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 Value

Return the sub string.

If length is 0 or negative, an empty string is returned.

Example


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.





Example 2

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.