1

I get the first slice of Banana:

let str = "Apple, Banana, Kiwi";
document.getElementById("demo").innerHTML = str.slice(7,13);

Now this one confuses me because it is zero based and shows this as the answer

let str = "Apple, Banana, Kiwi";
str.slice(-12, -6)    // Returns Banana

not sure why its not " "Banan - quotes mean a space and the -6 above includes the last character but it shouldn't as my example here shows because as javascript states with slice method the last number is not included. Hope you can help the confusion on my part??

1

1 Answer 1

1

If beginIndex or endIndex is negative then it is treated as

  • beginIndex = str.length + beginIndex
  • endIndex = str.length + endIndex

let str = "Apple, Banana, Kiwi";

const negativeStart = -12;
const negativeEnd = -6;

console.log(str.slice(negativeStart, negativeEnd)) // Returns Banana

const start = str.length + negativeStart;
const end = str.length + negativeEnd;
console.log(start);
console.log(end);
console.log(str.slice(start, end));

Sign up to request clarification or add additional context in comments.

1 Comment

I saw the example and read the Moz and yes it makes sense with the formula you used above and I can see how it works. My error was believing it started from the actual end and counted starting at 0, which seems I am wrong.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.