Hey everyone! I'm a complete newbie and I'm struggling to wrap my head around the `substr` method in JavaScript. I wrote this snippet of code:
```javascript
let sliceablestring = "this string can be sliced";
let cutstring = sliceablestring.substr(-4, 8);
console.log(cutstring);
```
It returned "iced", but I thought that negative indexes were supposed to start from 0. Can someone explain why I'm getting this output instead of something like "this str"? I would really appreciate any help!
3 Answers
Negative slice indices count from the end of the string. So when you use `-4`, it means starting from the fourth-to-last character, and you're asking for the next eight characters from there, which gives you "iced". Keep practicing, you'll get the hang of it!
You might want to check the documentation for `substr`. It really helps clear things up! Here's the link: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/substr
It looks like you're mixing up the `substr()` and `substring()` methods. With `substring()`, if you give it a negative number, it'll treat it as `0`. But for `substr()`, using a negative number means you're counting from the end of the string. So in your case, `-4` corresponds to the fourth-to-last character, which is the last "i" in "sliced", and then it takes 8 characters from there, resulting in "iced"!
Thank you so much! I realize now I confused the two methods, lol. That totally makes sense!
Ohhh, thanks for clarifying!