Help With Understanding the `substr` Method in JavaScript

0
3
Asked By CoconutCoder42 On

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

Answered By LearnToCode99 On

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!

CoconutCoder42 -

Ohhh, thanks for clarifying!

Answered By CodeNinja88 On

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

Answered By TechWiz123 On

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"!

CoconutCoder42 -

Thank you so much! I realize now I confused the two methods, lol. That totally makes sense!

Related Questions

LEAVE A REPLY

Please enter your comment!
Please enter your name here

This site uses Akismet to reduce spam. Learn how your comment data is processed.