The slice() method in JavaScript is used to extract a section of a string and return it as a new string.
Syntax: string.slice(startIndex, endIndex)
- string: The string from which we want to extract the substring.
- startIndex: The index where the extraction will begin. If negative, it counts from the end of the string.
- endIndex (optional): The index before which the extraction will end. If omitted, slice() extracts to the end of the string. If negative, it counts from the end of the string.
Example:
let str = "Hello, World!";
let slicedString = str.slice(7, 12);
console.log(slicedString); // Output: World
Explanation:
- We have a string str containing the text "Hello, World!".
- We use slice(7, 12) to extract a substring starting from index 7 (inclusive) to index 12 (exclusive).
- The extracted substring is "World", which is then stored in the variable slicedString and logged to the console.
Online code compiler: https://app.singhteekam.in/codecompiler/