Kaa1el Kaa1el - 1 year ago 73
Javascript Question

Why substring does not handle negative indices?

handles negative indices perfectly but
only accepts nonnegative indices.

Is there a reason of not using
in favor of
? The usage of negative indices are so useful in a lot of cases by viewing the space of indices as cyclic group. Why
is indicated "deprecated" by MDN?

Answer Source

substring is when you want to specify a starting and ending index. substr is when you want to specify a starting offset and a length. They do different things and have different use cases.

Edit: To better answer the exact question of
Why substring does not handle negative indices?

substring specifies a starting and ending index of characters in a string. substr deals with a starting offset and a length. It makes sense to me that substring does not allow a negative index, because there really isn't a such thing as a negative index (the characters in a string are indexed from 0 to n, a "negative index" would be out of bounds). Since substr is dealing with an offset vs an index, I feel the term offset is loose enough to allow for a negative offset, which of course means counting backwards from the end of the string rather than forward from the beginning. This might just be semantics, but its how I make sense of it.

Why is substr deprecated?

I would argue that is in fact not deprecated.

The revision history for the substr MDN states the deprecation notice was put in based on this blog post:

Aug 16, 2016, 12:00:34 AM hexalys add deprecated mention per https://blog.whatwg.org/javascript

Which states that the HTML string methods are deprecated (which they should be!). These are methods that wrap a string in an HTML tag, ie, "abc".sub() would return <sub>abc</sub>. The blog post lists out all of the HTML string methods, and imho, erroneously includes subtr as an HTML string method (it isn't).

So this looks like a misunderstanding to me.

(Excerpt below, emphasis added by me)


The infamous “string HTML methods”: String.prototype.anchor(name), String.prototype.big(), String.prototype.blink(), String.prototype.bold(), String.prototype.fixed(), String.prototype.fontcolor(color), String.prototype.fontsize(size), String.prototype.italics(), String.prototype.link(href), String.prototype.small(), String.prototype.strike(), String.prototype.sub(), String.prototype.substr(start, length), and String.prototype.sup(). Browsers implemented these slightly differently in various ways, which in one case lead to a security issue (and not just in theory!). It was an uphill battle, but eventually browsers and the ECMAScript spec matched the behavior that the JavaScript Standard had defined.