Saturday, January 18, 2025
HomeQ&AWhat is JavaScript String slice() Method?

What is JavaScript String slice() Method?

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`).

See also  Is Purple Really A Good Brand ?

### 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.

See also  What are the lyrics to Applebee's birthday song?

### 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.

RELATED ARTICLES
0 0 votes
Article Rating

Leave a Reply

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
- Advertisment -

Most Popular

Recent Comments

0
Would love your thoughts, please comment.x
()
x