Description
The JavaScript String method slice()
extracts and returns a section of a string based on the given index values.
- It generates and returns a new string, and it doesn't modify the original string.
- The starting index is inclusive and the ending index is exclusive.
Syntax
The method slice()
has the below syntax, where str
is a string.
str.slice(beginIndex, endIndex)
Parameters
The method slice()
allows the below parameters.
beginIndex
- It is the starting index for selection.
- This index is inclusive, which means the extraction includes the character in this index.
endIndex
(optional)
- It is the ending index for selection.
- This index is exclusive, which means the extraction doesn't include the character in this index.
- If it is not provided, then the end of the string is considered.
Result
Returns a new string containing the extracted section of a string, based on given index values.
It doesn't modify the original string.
Example 1: Using the Method
The below example shows the basic usage of the method.
var str = "Learning JavaScript is fun";
// Using both start and end indices
document.write(str.slice(9, 19)); // Prints: JavaScript
// Using only start index
document.write(str.slice(9)); // Prints: JavaScript is fun
Output:
JavaScript
JavaScript is fun
Example 2: Method with Negative Indices
If we need to extract a portion of a string from the end, then we can use negative indices.
The negative indices are counted from backward, where -1
represents the last element, -2
represents the second element, and so on.
var str = "Learning JavaScript is fun";
// Using both start and end indices
document.write(str.slice(-17, -7)); // Prints: JavaScript
// Using only start index
document.write(str.slice(-17)); // Prints: JavaScript is fun
Output:
JavaScript
JavaScript is fun
Example 3: Method without Indices
If the indices are not provided, the method returns the complete string.
var str = "Learning JavaScript is fun";
// Method without indices
document.write(str.slice()); // Prints: Learning JavaScript is fun
Output:
Learning JavaScript is fun
Overall
The JavaScript String method slice()
extracts and returns a section of a string based on the given index values.