Javascript Reference - JavaScript String slice() Method








slice(startingPosition [, whereToStop(exclusive)]) returns a substring and accepts either one or two arguments.

If the second argument is omitted, it is default to the ending position. slice() does not alter the value of the string itself.

The first character has the position 0, the second has position 1, and so on.

Use a negative number to start from the end of the string.

Browser Support

slice() Yes Yes Yes Yes Yes




Syntax

stringObject.slice(start, end);

Parameter Values

Parameter Description
start Required. where to start. First character is at position 0
end Optional. Where to end, not including. Default to to the end of the string

Return Value

A sub string.

Example


var stringValue = "hello world"; 
console.log(stringValue.slice(3)); //"lo world" 

The code above generates the following result.





Example 2

A negative argument tells to do the sub string from the end.


var stringValue = "hello world"; 
        
console.log(stringValue.slice(-3)); //"rld" 
console.log(stringValue.slice(3, -4)); //"lo w" 

The code above generates the following result.