String.prototype.until

Michael A. Smith michael at smith-li.com
Mon Jan 2 09:48:36 PST 2012


Semantically, calling it "until" makes me think that if the "needle"
isn't found, it should return the entire haystack. Your example
implementation would return an empty string in that case. Also, to
keep consistency with other string methods like substr, shouldn't we
allow the developer to decide the starting index?

String.prototype.until = function (start, needle) {
    return "" + (this.substr(start, this.indexOf(needle)) || this);
}

(The ["" +] part is probably not necessary, but it makes it easier to
see the implementation work in the console.)

Michael A. Smith
Web Developer
True Action Network (an eBay Company)

On Mon, Jan 2, 2012 at 12:03 PM, Adam Shannon <adam at ashannon.us> wrote:
> Hello all,
>
> I recently ran into a situation where I would like to obtain a
> substring from the beginning until the first encounter with another
> substring. This promoted me to write a simple function, called until
> and I wondered if it would be something to add with the other string
> extras for ES.next.
>
> It could be defined as acting the same way as the following code:
>
> String.prototype.until = function (needle) {
>  return this.substr(0, this.indexOf(needle));
> }
>
> --
> Adam Shannon
> Web Developer
> University of Northern Iowa
> Sophomore -- Computer Science B.S. & Mathematics
> http://ashannon.us
> _______________________________________________
> es-discuss mailing list
> es-discuss at mozilla.org
> https://mail.mozilla.org/listinfo/es-discuss
>


More information about the es-discuss mailing list