JavaScript slice() Method: Extract Substrings Safely
This Snippet is coded by a user inOnline javascript Compiler. You can see and run this code too.
زبان: JavaScript
How slice() works
The JavaScript slice() method extracts a section of a string and returns it as a new string without changing the original. It accepts two optional arguments: startIndex and endIndex. The startIndex is inclusive, while endIndex is exclusive. If endIndex is omitted, extraction continues to the end of the string. Negative indexes count backward from the end, so -1 refers to the last character. If the computed start is greater than the computed end, the method returns an empty string.
Inputs and outputs: str.slice(start, end) takes numeric indexes (or values coerced to numbers) and outputs a substring. For example, 'JavaScript'.slice(0, 4) returns 'Java', while 'JavaScript'.slice(-6) returns 'Script'. Because strings are immutable, the source string remains unchanged. Common use cases include trimming prefixes, removing file extensions, and isolating parts of a formatted value.
Time complexity: slice() runs in O(k) time, where k is the number of characters copied into the returned substring. In the worst case, extracting nearly the whole string is O(n), where n is the string length. Space complexity is O(k) for the new string. Unlike substring(), slice() accepts negative offsets, making end-relative extraction convenient. Use slice() when you need safe, readable substring extraction with support for negative indexes and no mutation. Always pass numbers to avoid coercion surprises.