Alexander Mills
Alexander Mills

Reputation: 100320

Why slice(-x,0) doesn't produce expected string

If I have this:

console.log('12345'.slice(-3)); // I get '345'

but when I do:

console.log('12345'.slice(-3, 0)); // I get '' (empty string).

what is the reasoning behind this? It makes no sense to me. Is there a JS API that can wrap around strings like I expect here? (I was expecting '345' again.)

Upvotes: 0

Views: 52

Answers (1)

CertainPerformance
CertainPerformance

Reputation: 371138

The second parameter is the index where the substring to be extracted ends (exclusive). If that index is before (or equal to) the start index (the first parameter), the result is the empty string.

As the docs say about the second parameter:

If end is positioned before or at start after normalization, nothing is extracted.

After normalization, .slice(-3) is equivalent to .slice(2), and the second parameter defaults to the length of the string, so

.slice(-3)
// equivalent to
.slice(2)

is like

.slice(2, 5) // take the substring from index 2 to index 5

and not

.slice(2, 0)

Upvotes: 5

Related Questions