The slice() method of the String class in JavaScript extracts a section of a string and returns it as a new string, without modifying the original string.
There are 2 variations for the syntax of String.slice() method. They are:
slice(indexStart)
Parameters
Parameter | Optional/Required | Description |
---|---|---|
indexStart | required | The zero-based index at which to begin extraction. A negative index can be used, indicating an offset from the end of the string. |
This method extracts a section of a string starting from the given indexStart to the end of the string.
Returns value of type String
.
slice(indexStart, indexEnd)
Parameters
Parameter | Optional/Required | Description |
---|---|---|
indexStart | required | The zero-based index at which to begin extraction. A negative index can be used, indicating an offset from the end of the string. |
indexEnd | optional | The zero-based index before which to end extraction. The character at this index will not be included. If omitted, extraction continues to the end of the string. A negative index can be used, indicating an offset from the end of the string. |
This method extracts a section of a string starting from the given indexStart up to, but not including, the specified indexEnd.
Returns value of type String
.
In JavaScript, we can use the slice()
method to extract a section of a string starting from the specified index to the end of the string.
For example,
str
with the value 'Hello, world!'
.slice()
method with the start index 7
.'world!'
, is stored in the variable slicedStr
.slicedStr
to the console using console.log()
method.const str = 'Hello, world!';
const slicedStr = str.slice(7);
console.log(slicedStr);
'world!'
In this example, we use the slice()
method to extract a section of a string starting from the specified start index and ending at, but not including, the specified end index.
For example,
str
with the value 'Hello, world!'
.slice()
method with the start index 0
and the end index 5
.'Hello'
, is stored in the variable slicedStr
.slicedStr
to the console using console.log()
method.const str = 'Hello, world!';
const slicedStr = str.slice(0, 5);
console.log(slicedStr);
'Hello'
This example demonstrates how to use the slice()
method with negative indices to extract a section of a string from the end.
For example,
str
with the value 'Hello, world!'
.slice()
method with the start index -6
to extract the last six characters.'world!'
, is stored in the variable slicedStr
.slicedStr
to the console using console.log()
method.const str = 'Hello, world!';
const slicedStr = str.slice(-6);
console.log(slicedStr);
'world!'
In this JavaScript tutorial, we learned about slice() method of String: the syntax and few working examples with output and detailed explanation for each example.