String.prototype.slice()
The slice()
method extracts a section of a string and
returns it as a new string, without modifying the original string.
Syntax
slice(indexStart)
slice(indexStart, indexEnd)
Parameters
indexStart
- : The index of the first character to include in the returned substring.
indexEnd
optional- : The index of the first character to exclude from the returned substring.
Return value
A new string containing the extracted section of the string.
Description
slice()
extracts the text from one string and returns a new string. Changes to the text in one string do not affect the other string.
slice()
extracts up to but not including indexEnd
. For example, str.slice(1, 4)
extracts the second character through the fourth character (characters indexed 1
, 2
, and 3
).
- If
indexStart >= str.length
, an empty string is returned. - If
indexStart < 0
, the index is counted from the end of the string. More formally, in this case, the substring starts atmax(indexStart + str.length, 0)
. - If
indexStart
is omitted, undefined, or cannot be converted to a number (usingNumber()
), it's treated as0
. - If
indexEnd
is omitted, undefined, or cannot be converted to a number (usingNumber()
), or ifindexEnd >= str.length
,slice()
extracts to the end of the string. - If
indexEnd < 0
, the index is counted from the end of the string. More formally, in this case, the substring ends atmax(indexEnd + str.length, 0)
. - If
indexEnd <= indexStart
after normalizing negative values (i.e.indexEnd
represents a character that's beforeindexStart
), an empty string is returned.