What is the difference between String.slice and String.substring in JavaScript?
Table of Contents
Introduction
In JavaScript, String.slice and String.substring are two methods used to extract a portion of a string. While they serve similar purposes, they have distinct differences in terms of syntax and behavior.
What is String.slice?
Definition
String.slice extracts a section of a string and returns it as a new string. The extraction starts at the specified start index and ends at the specified end index (not inclusive).
Syntax
- startIndex: The index at which to start extraction.
- endIndex (optional): The index at which to end extraction (exclusive). If omitted, it extracts to the end of the string.
Characteristics
- Negative Indices: Can accept negative indices, counting from the end of the string.
- Returns: A new string containing the extracted section.
Example
What is String.substring?
Definition
String.substring extracts characters from a string between two specified indices and returns the new substring.
Syntax
- startIndex: The index at which to start extraction.
- endIndex (optional): The index at which to end extraction (exclusive). If omitted, it extracts to the end of the string.
Characteristics
- No Negative Indices: Does not accept negative indices; negative values are treated as
0. - Swapping Indices: If
startIndexis greater thanendIndex,substringswaps them. - Returns: A new string containing the extracted characters.
Example
Key Differences
- Handling of Negative Indices:
- slice: Accepts negative indices, counting from the end.
- substring: Treats negative indices as
0.
- Swapping Indices:
- slice: Does not swap indices; if
startIndexis greater thanendIndex, it returns an empty string. - substring: Swaps indices if
startIndexis greater thanendIndex.
- slice: Does not swap indices; if
- Return Values:
- Both methods return a new string, but their extraction behavior differs based on the conditions mentioned.
Conclusion
In conclusion, while String.slice and String.substring can both be used to extract portions of strings in JavaScript, they have key differences in handling indices and their behavior. Understanding these distinctions is essential for effective string manipulation in your JavaScript applications.