JavaScript String slice() Method
Last Updated : 12 Jul, 2024
Improve
The slice()
method in JavaScript is used to extract a portion of a string and create a new string without modifying the original string.
Syntax:
string.slice(startingIndex, endingIndex);
Parameters:
This method uses two parameters. This method does not change the original string.
- startingIndex: It is the start position and it is required(The first character is 0).
- endingIndex: (Optional)It is the end position (up to, but not including). The default is string length.
Return Values:
It returns a part or a slice of the given input string.
Example 1: Slicing String
The code slices the string “Geeks for Geeks” into three parts using the slice() method based on specified indices and logs each part separately.
let A = 'Geeks for Geeks';
b = A.slice(0, 5);
c = A.slice(6, 9);
d = A.slice(10);
console.log(b);
console.log(c);
console.log(d);
Output
Geeks for Geeks
Example 2: Negative start or end index case
The code slices the string “Ram is going to school” into multiple parts using the slice() method with various index combinations and logs each part separately.
let A = 'Ram is going to school';
// Calling of slice() Method
b = A.slice(0, 5);
// Here starting index is 1 given
// and ending index is not given to it so
// it takes to the end of the string
c = A.slice(1);
// Here endingindex is -1 i.e, second last character
// of the given string.
d = A.slice(3, -1);
e = A.slice(6);
console.log(b);
console.log(c);
console.log(d);
console.log(e);
Output
Ram i am is going to school is going to schoo going to school