JavaScript slice method

The JavaScript slice method extract parts of a string and returns the extracted parts in a new string.
Use the start and end parameters to specify the part of the string you want to extract.
The first character has the position 0, the second has position 1, and so on.
Use a negative number to select from the end of the string.

Syntax:

string.slice(start,end)

Where,
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 omitted,  slice() selects all characters from the start-position to the end of the string.

Example:

var str=”The JavaScript slice() method for string.”;
var n = ”;

// Fetch first character of the string
n=str.slice(0,1);
alert(n); // OUTPUT: T

// fetch specific number of characters from string
n =str.slice(4,23);
alert(n); // OUTPUT: JavaScript slice()

// fetch specific number of characters starts from righthand side string
n =str.slice(-11,50);
alert(n); // OUTPUT: for string.

Live Demo: JavaScirpt slice method

Leave a Reply