JavaScript string slice method

JavaScript slice method is used to create a substring from a given string

specify the index of substring in slice as a parameter

Syntax

slice()

slice(startIndex);

slice(startIndex,endIndex);

slice method return new string as form of substring without modifying original string

Example

Browser support

Browser
Versionyes
yes
yes
yes
yes

Parameter Details

ParameterDescription
startIndexstarting index decide  begin extracting the original string
Tips - when you pass negative Index then startIndex treated as startIndex = str.length + index(negative)
Tips - when pass startIndex greater than string then it return empty string
endIndexoptional - endIndex decide the end of extracting original string
Tips - Length of endIndex greater than length of string also support
Tips - when endIndex is negative then endIndex treated as endIndex = str.length + index(negative)

Technical Details

Return value
slice method return substring without changing original string

Positive StartIndex

Example

Negative startIndex

when pass negative number then startIndex treated as startIndex = str.length+number(negative)

Example

Positive endIndex

Example

Negative endIndex

when pass negative index then endIndex treated as endIndex = str.length+index(negative)

Example

Important - If endIndex is less than startIndex then it return empty string

Example