Slice vs Substring vs Substr in JavaScript: Key Differences and Usage
slice extracts a part of a string using start and end indexes and supports negative indexes. substring also extracts between two indexes but swaps them if start is greater than end and does not support negative indexes. substr extracts a substring starting at an index for a given length but is deprecated and should be avoided.Quick Comparison
Here is a quick table comparing slice, substring, and substr methods in JavaScript.
| Feature | slice | substring | substr |
|---|---|---|---|
| Parameters | start, end (end not included) | start, end (end not included) | start, length |
| Negative indexes | Supported (counts from end) | Not supported (treated as 0) | Supported (negative start counts from end) |
| Swaps indexes if start > end | No | Yes | No |
| Deprecated | No | No | Yes (avoid usage) |
| Use case | Extract part by indexes, supports negative | Extract part by indexes, safe swapping | Extract part by start and length |
Key Differences
slice and substring both extract parts of a string using two indexes, but they handle parameters differently. slice allows negative indexes to count from the string's end, making it flexible for extracting from the back. substring treats negative indexes as zero and swaps the start and end if start is greater than end, ensuring the start is always less than end.
substr differs by taking a start index and a length of characters to extract, not an end index. It also supports negative start indexes. However, substr is deprecated and should be avoided in modern code.
Choosing between slice and substring depends on whether you want negative index support or automatic swapping of indexes. slice is generally preferred for its flexibility and clarity.
Code Comparison
Using slice to extract the word "world" from a string:
const text = "Hello world!"; const result = text.slice(6, 11); console.log(result);
substring Equivalent
Using substring to extract the same word "world" from the string:
const text = "Hello world!"; const result = text.substring(6, 11); console.log(result);
When to Use Which
Choose slice when you want to use negative indexes or prefer clear start and end positions without automatic swapping. Choose substring when you want the method to handle swapped indexes gracefully and do not need negative index support. Avoid substr as it is deprecated and may be removed in future JavaScript versions.
Key Takeaways
slice supports negative indexes and does not swap parameters.substring swaps parameters if start is greater than end and does not support negative indexes.substr uses start and length but is deprecated and should be avoided.slice for flexible, modern string extraction.substring if you want automatic index swapping without negative index support.