#62: 'hello world'.slice(-5, -1)
Topic: strings · Difficulty: ★
console.log('hello world'.slice(-5));
console.log('hello world'.slice(-5, -1));Output
world worl
Why
Negative indices in slice() count backward from the end of the string rather than forward from the start: -5 refers to the 5th character from the end. 'hello world' is 11 characters long, so index -5 lands on 'w', and slice(-5) with no end argument takes everything from there to the end, giving 'world'. slice(-5, -1) additionally caps the end at index -1, which is one character before the very end — so it stops just short of the final 'd', producing 'worl'. Mixing negative start and end indices is a concise way to grab a suffix while trimming one or more trailing characters without needing to know the string's exact length.