JavaScript slice() method
The slice()
method in JavaScript is used to extract a portion of a string (or an array) and return it as a new string (or array) without modifying the original. This method allows you to specify a starting index and an optional ending index to determine the part of the string or array to extract.
Syntax:
startIndex
: The index at which to begin extraction. The extraction will start from this index (inclusive).endIndex
(optional): The index at which to end extraction. The extraction will stop at this index (exclusive). If this parameter is not provided,slice()
will extract to the end of the string.
Return Value:
- Returns a new string (or array) that contains the extracted portion of the original string (or array). The original string (or array) remains unchanged.
Example 1: Basic Usage
In this example, slice(7, 12)
extracts the substring starting at index 7
and ending just before index 12
, resulting in "World"
.
Example 2: Omitted End Index
If you omit the endIndex
, slice()
will extract characters from the startIndex
to the end of the string.
Here, slice(7)
extracts the substring from index 7
to the end of the string.
Example 3: Negative Indices
You can also use negative indices with slice()
. A negative index counts back from the end of the string (or array).
In this example, slice(-6, -1)
extracts characters starting from the sixth character from the end up to (but not including) the last character.
Example 4: Handling Indices Out of Range
If startIndex
is greater than or equal to the length of the string, slice()
will return an empty string. Similarly, if endIndex
is out of range, it will adjust to the string's length.
Example 5: Using slice()
with Arrays
The slice()
method can also be used on arrays to extract a portion of the array.
In this example, slice(1, 4)
extracts elements from index 1
to index 4
(exclusive).
Example 6: Original String and Array Remain Unchanged
The slice()
method does not modify the original string or array.
Summary:
- The
slice()
method extracts a portion of a string or array and returns it as a new string or array. - It takes two parameters:
startIndex
(inclusive) andendIndex
(exclusive). - If the
endIndex
is omitted, the method extracts to the end of the string or array. - Negative indices can be used to count back from the end.
- The method does not modify the original string or array; it returns a new instance.