slice method

Javascript slice() method:

Slice() method extracts a part of string and returns a new string without modifying the original string. It requires the index as start and end parameters for returning part of the string. Here negative index are allowed.

Syntax:

slice(indexStart)

slice(indexStart, indexEnd)

Here the parameter indexEnd is optional.

indexStart – index of first character to include in the returned string. If negative, this argument specifies a position from the end of the string. For example -1 indicates the last character and -2 indicates the second character from last.

indexEnd – index of first character to exclude from the returned string. As this is optional if not specified it includes all character from indexStart to end of string. Same as above, if negative argument, it specifies  a position measured from the end of the string.

Return value – A new string containing the extracted section of the string.

Example:
const s = 'Abaython';
console.log(s.slice(0,4))  
console.log(s.slice(2,4))  
console.log(s.slice(4))      
console.log(s.slice(3,-1)) 
console.log(s.slice(3,-2))  
console.log(s.slice(-3,-1))
Output:

Abay

ay

thon

ytho

yth

ho

indexStart>=index.length?

It returns an empty string.

indexStart omitted?

If indexStart is omitted, undefined or cannot be converted to a number. It consider indexStart as 0 and returns from  the start of the string.

const s = 'Abaython';
s.slice()
Output:

‘Abaython’

String methods slice(), substring() and the deprecated substr() all return specified portions of a string. Slice() is more flexible than substring() because it allows negative index values. Slice() differs from substr() in that it specifies a substring with two character positions, while substr() uses one position and a length. String.slice() is an analog of Array.slice()