JavaScript String slice() Method Examples
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
We have a complete list of Javascript string methods, to check those please go through this Javascript String Complete reference article.
Supported Browser:
We have a Cheat Sheet on Javascript where we covered all the important topics of Javascript to check those please go through Javascript Cheat Sheet-A Basic guide to JavaScript.
JavaScript String slice() Method
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.
Contact Us