Animations
API
Arrays
Async
Basics
Challenges
Classes
Console
Dates
Debugging
DOM Elements
DOM Methods
DOM Properties
Event Listeners
Flow Control
Forms
Functions
Global Functions
JSON
Keywords
Libraries (3rd party)
Math
Modules
Objects
Snippets
String
Types
Widgets
Window Object
slice()
extracts a part of a string and returns the extracted part in a new string. The method takes 2 parameters: the
starting index (position), and the ending index (position).
This example slices out a portion of a string from position 7 to position 13:
let str = "Apple, Banana, Kiwi";
document.getElementById("demo1").innerHTML = str.slice(7, 13);
If a parameter is negative, the position is counted from the end of the string. This example slices out a portion of a string from position -12 to position -6:
let str2 = "Apple, Banana, Kiwi";
document.getElementById("demo2").innerHTML = str2.slice(-12, -6);
If you omit the second parameter, the method will slice out the rest of the string.
let str3 = "Apple, Banana, Kiwi";
document.getElementById("demo3").innerHTML = str3.slice(4);