JavaScript tutorial:
slice method (String)

 

The slice method returns a section of a string.

Syntax

stringObj.slice(start, [end])

The slice method syntax has these parts:

Part

Description

stringObj

Required. A String object or literal.

start

Required. The zero-based index of the beginning of the specified portion of stringObj.

end

Optional. The zero-based index of the end of the specified portion of stringObj.

Return value

The slice method returns a section of a string.

Example

The slice method returns a String object containing the specified portion of stringObj.

If negative, end indicates an offset from the end of stringObj. In addition, it is not zero-based. If omitted, extraction continues to the end of stringObj.

//the code below show how the slice function work
document.writeln("I want to slice an apple".slice(0));
document.writeln("I want to slice an apple".slice(10,24));

  To run the code, paste it into JavaScript Editor, and click the Execute button.

See also: slice method (Array), String Object methods