extraction
String.prototype.slice
Extracts a section of the string from beginIndex up to but not including endIndex, returning a new string. Negative indices count from the end.
str.slice(beginIndex[, endIndex]) Parameters
| Parameter | Purpose |
|---|---|
| beginIndex | Start position (negative counts from end) |
| endIndex | Exclusive end position (default str.length; negative counts from end) |
Examples
console.log('hello world'.slice(0, 5)); Prints 'hello'
console.log('hello world'.slice(-5)); Prints 'world'
console.log('hello'.slice(1, -1)); Prints 'ell'
console.log('hello'.slice(3, 1)); Prints '' (end before start)
Gotcha
Unlike substring, slice does NOT swap arguments — if end < start you get an empty string. Negative indices are the main reason to prefer slice over substring.
Related methods
String.prototype.substring
Returns a new string between indexStart and indexEnd (exclusive). Unlike slice(), negative arguments are treated as 0 and the arguments are swapped when indexStart > indexEnd.
String.prototype.substr
Returns a portion of the string starting at start with the specified length. Deprecated as a legacy web feature — new code should use slice or substring, but implementations still ship it.
String.prototype.at
Returns the UTF-16 code unit at the given index as a single-character string, supporting negative indices that count from the end. Added in ES2022 as a cleaner alternative to str[str.length - 1].
String.prototype.codePointAt
Returns the full Unicode code point (0–0x10FFFF) starting at the given position, correctly combining surrogate pairs. Added in ES2015 as the Unicode-safe counterpart to charCodeAt.