The slice() method in JavaScript is used to extract a section of a string and return a new string. The method takes two arguments: the starting index and the ending index of the section you want to extract. The starting index is inclusive and the ending index is exclusive. Here is an example of how to use the slice() method:
let str = "Hello, world!";
let sliced = str.slice(7, 12);
console.log(sliced); // Output: "world"
In the example above, the slice() method is called on the string “Hello, world!” and the arguments passed in are 7 and 12. This extracts the substring “world” (starting at index 7 and ending at index 12, exclusive) and assigns it to the variable sliced.
You can also use negative indices, if you want to slice from end of the string.
let str = "Hello, world!";
let sliced = str.slice(-5);
console.log(sliced); // Output: "world"
In this example, the slice() method is called on the string “Hello, world!” and the argument passed in is -5. This extracts the substring “world” (starting from -5th index from the end and ending at the end of the string) and assigns it to the variable sliced.
The slice() method can also be used with arrays in JavaScript. It works similarly to how it works with strings, but instead of returning a substring, it returns a new array that contains the selected elements.
Here is an example of how to use the slice() method with an array:
let arr = [1, 2, 3, 4, 5];
let sliced = arr.slice(1, 3);
console.log(sliced); // Output: [2, 3]
In this example, the slice() method is called on the array [1, 2, 3, 4, 5] and the arguments passed in are 1 and 3. This extracts the elements of the array [2, 3] (starting at index 1 and ending at index 3, exclusive) and assigns it to the variable sliced.
You can also use negative indices, if you want to slice from end of the array.
let arr = [1, 2, 3, 4, 5];
let sliced = arr.slice(-3);
console.log(sliced); // Output: [3, 4, 5]
In this example, the slice() method is called on the array [1, 2, 3, 4, 5] and the argument passed in is -3. This extracts the elements of the array [3, 4, 5] (starting from -3rd index from the end and ending at the end of the array) and assigns it to the variable sliced.
It’s worth noting that the original array is not modified by the slice() method, it creates a new array with the selected elements.