fromIndex for

Felix Böhm esdiscuss at
Fri Apr 20 11:20:46 PDT 2012

In December of 2009, there was already a related proposal [1] (which pretty
much got ignored at that time), but I wanted to ask only for a subset of it:

When building parsers, the second argument of String.prototype.indexOf
(named firstIndex) is pretty helpful to speed things up. A simple index can
be used to track the current position. In more general cases (with more
than just a handful of separators), appears to be
the better choice. But lacking the firstIndex parameter, it requires to use
String.prototype.substr after each iteration. This leads to slow and
bad-looking code. But there's a solution: A firstIndex parameter for

A polyfill could look like this (expecting that the number of arguments is
increased to 2):

if ( === 1) { = (function (oldSearch) {
        return function (re, fromIndex) {
            if (typeof fromIndex !== "number") return,
            var result =, fromIndex), re)
            return result === -1 ? result : result + fromIndex;

The only reason I can think of why this might be a bad idea is the "^"
metacharacter, as it's accepting the new position as the start of the
string. The optimal/expected behavior in this case might need some
discussion (even though the solution above eases polyfilling a lot).

The only response to the old proposal suggested using re.lastIndex, what's
just ugly and feels hacky.

-------------- next part --------------
An HTML attachment was scrubbed...
URL: <>

More information about the es-discuss mailing list