Javascript - String slice() Method

The slice() method extracts parts of a string and returns the extracted parts as new string.

Description

The slice() method extracts parts of a string and returns the extracted parts as new string.

You can use the start and end index to extract the string you want.

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

You can use the negative number to select from the end of the string.

Syntax

string.slice(start,end)

Parameter Values

Parameter Require Description
start Required.The position where to begin the extraction. First character is at position 0
end Optional. The position (up to, but not including) where to end the extraction.

If the end index is omitted, slice() selects all characters from the start-position to the end of the string.

Return

A String, representing the extracted part of the string

Example

Extract parts of a string:

Demo

//display the extracted part of the string.
var str = "Hello world!";
var res = str.slice(1, 5);
console.log(res);//from   w  w w  . j av  a  2 s  .c o  m

//Extract the whole string:
var str = "Hello world!";
var res = str.slice(0);
console.log(res);

//Extract from position 3, and to the end:
var str = "Hello world! test test";
var res = str.slice(3);
console.log(res);

//Extract the characters from position 3 to 8:
var str = "Hello world! test test";
var res = str.slice(3, 8);
console.log(res);

//Extract only the first character:
var str = "Hello world!";
var res = str.slice(0,1);
console.log(res);

//Extract only the last character:
var str = "Hello world!";
var res = str.slice(-1);
console.log(res);

Result