The `slice()` method in JavaScript is used to extract a section of a string and return it as a new string without modifying the original string. The syntax is as follows:
“`javascript
str.slice(startIndex, endIndex);
“`
– **`startIndex`** (required): The index at which to begin the extraction. The character at this position will be included in the new string.
– **`endIndex`** (optional): The index at which to end the extraction (but the character at this index will not be included). If not specified, `slice()` will extract until the end of the string.
### Example 1: Basic usage
“`javascript
let text = “Hello, world!”;
let result = text.slice(0, 5);
console.log(result); // Output: “Hello”
“`
In this example, `slice(0, 5)` extracts characters from index `0` to `4` (not including index `5`).
### Example 2: Using negative indices
The `slice()` method also supports negative values for indices, which count from the end of the string.
“`javascript
let text = “Hello, world!”;
let result = text.slice(-6, -1);
console.log(result); // Output: “world”
“`
Here, `-6` means the 6th character from the end, and `-1` refers to the last character, which is not included.
### Example 3: Omitting the `endIndex`
If the `endIndex` is omitted, `slice()` extracts characters from the `startIndex` to the end of the string.
“`javascript
let text = “JavaScript”;
let result = text.slice(4);
console.log(result); // Output: “Script”
“`
### Example 4: Start index larger than end index
If the `startIndex` is larger than the `endIndex`, an empty string will be returned.
“`javascript
let text = “Example”;
let result = text.slice(5, 3);
console.log(result); // Output: “”
“`
### Key Notes:
– `slice()` does not modify the original string, it returns a new string.
– Negative indices allow you to count from the end of the string.
– If the `startIndex` is greater than or equal to the length of the string, an empty string will be returned.