String.indexOf/lastIndexOf/search should have optional arguments fromIndex/toIndex

Karsten Düsterloh mnyromyr at tprac.de
Tue Dec 29 04:36:20 PST 2009


[I originally filed this as Mozilla bug 524907 and 524912, where it was
suggested that I bring up this topic here as well.]

Currently, String.indexOf/lastIndexOf do take a second parameter to
specify where to start the search, but none for where to stop.
String.search doesn't even allow to specify the start index.

Hence I'd propose to implement a String.substring-like signature for
these three methods:

  String.indexOf(searchValue[, fromIndex[, toIndex]])
  String.lastIndexOf(searchValue[, fromIndex[, toIndex]])
  String.search(regex[, fromIndex[, toIndex]])

Motivation:

Let d be a set of delimiters and s be a long string including several of
these delimiters in arbitrary order and count. Now try to process each
block of text between two such delimiters in dependance upon the
surrounding delimiters:
- looping over each single character in s and comparing it from JS is
slow (not so much in Gecko 1.9 as in Gecko 1.8, but still)
- s.indexOf is useless, because it only can check for one single
delimiter at a time, so you'd need one indexOf per delimiter, which may
result in completely parsing s for each delimiter!
- s.search(/[delimiters]/) is useless, because it always starts
searching at index 0 - you would have to cut/change s after each find

In theory, String.replace(regex, function) would be perfect for doing
this, but I believe that the additional, optional arguments
fromIndex/toIndex do make sense in their own right.


Karsten




More information about the es-discuss mailing list