Character indexing on strings
# P T Withington (18 years ago)
On 2007-06-13, at 20:47 EDT, Jeff Walden wrote:
it'd be nice if for negative values the index were calculated from
the end of the string
Agree. This is a common expectation and useful.
# Brendan Eich (18 years ago)
On Jun 14, 2007, at 6:10 AM, P T Withington wrote:
On 2007-06-13, at 20:47 EDT, Jeff Walden wrote:
it'd be nice if for negative values the index were calculated from the end of the string
Agree. This is a common expectation and useful.
At this point, the right thing is to file a trac ticket against the
Proposals component. We can morph it into a RefImpl bug after fixing
it in the wiki. Jeff, I'll give you dibs on this. Thanks,
As described in the exported wiki right now, indexing on strings is equivalent to calling String.prototype.charAt on the string. charAt returns "" for out-of-bounds values if I remember right, but it'd be nice if for negative values the index were calculated from the end of the string, as will occur with slice syntax (on strings, I might add), basically like so:
function index(str, ix) { if (ix < 0) ix += str.length; return str.charAt(i); }
The resultant inequality of charAt and indexing isn't ideal, but I think syntactic similarity makes it more important that slice notation and index notation be consistent.
(For completeness I note that str[-1] == str.length in SpiderMonkey, but I don't know of anyone else who implements this, and the current proposal contradicts this anyway. :-) )