fromIndex for String.prototype.search

Felix Böhm esdiscuss at feedic.com
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), String.prototype.search 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
String.prototype.slice.

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

if (String.prototype.search.length === 1) {
    String.prototype.search = (function (oldSearch) {
        return function (re, fromIndex) {
            if (typeof fromIndex !== "number") return oldSearch.call(this,
re);
            var result = oldSearch.call(this.substr(0, fromIndex), re)
            return result === -1 ? result : result + fromIndex;
        };
    })(String.prototype.search);
}

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.

[1] https://mail.mozilla.org/pipermail/es-discuss/2009-December/010505.html
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.mozilla.org/pipermail/es-discuss/attachments/20120420/8664abf8/attachment.html>


More information about the es-discuss mailing list