Hacker News new | ask | show | jobs
by chrismorgan 990 days ago
> For languages like JavaScript, Java and C#, it's probably a method, so you can start typing. Might be substring(), might also be substr() or something like that.

In JavaScript, there are both, and a third one besides, largely for reasons of historical accumulation and inconsistent implementation:

  String.prototype.substr(start, length?)
  String.prototype.substring(start, end?)
  String.prototype.slice(start, end?)
They’ve each got their strange nuances in behaviour (and, in so-ancient-you-certainly-don’t-care-about-them engines, cross-engine inconsistencies), so if you’re relying on autocomplete, it’s necessary that your autocomplete at the very least give some meaningful parameter names, because the difference between taking length and an end index is rather significant.

Which one should you use? slice. It’s generally agreed to be the most reasonable of the three in what it does and how it works, and it matches Array.prototype.slice well. So: sorry that you thought it might be substring or substr, because those exist but you probably shouldn’t use them.

(Related reading: https://stackoverflow.com/questions/2243824/what-is-the-diff....)