Should String.prototype.split accept variable arguments optionally?

Benjamin (Inglor) Gruenbaum inglor at gmail.com
Wed Oct 16 05:54:14 PDT 2013


Splitting by one value or another seems to be a pretty common use case if
Stack Overflow questions and personal experience are an indication. For
example "-" and " " and "/".

Currently, the solution is to pass a regular expression to
String.prototype.split .

However, it would be nice to be able to pass variable arguments to the
method.

So if I want to split strings like "0-12-12" and "321+32/14" or "TI-CK ER"
instead of having to do:

```
    myString.split(/ |-|\/|\+/g); // this is no fun to read

    myString.split(" ","-","/","+"); // this is easier
    myString.split([" ","-","/","+"]); // this is also easier.

```

The advantage of the second one (accepting an Array) is that it does not
require additional handling of the second "limit" parameter.

A possible advantage of the first one is that it's simpler.

The algorithm for the second one could be quite simple, in 21.1.3.17 only
_SplitMatch_ needs to be updated, and implementation sounds pretty simple
in engines and the semantics simple in the spec.

Some other languages:

 - C# accepts an array of `char` or array of "string" in its Split,
http://msdn.microsoft.com/en-us/library/tabh47cf.aspx
 - Ruby doesn't do this with `.split`, behaves like JS
http://ruby-doc.org/core-2.0.0/String.html#method-i-split
 - Java String.split only accepts a regex
 - Python doesn't do this with `.split`

Advantages:
 - Nice api addition that solves a common use case.
 - A way to split by multiple delimiters easily without knowledge of
regular expressions.
 - Does not break the existing API, especially if we use array syntax.

Disadvantages
 - Extra overhead
 - Use case needs assertion

(Reminds me of stuff in string_extras
http://wiki.ecmascript.org/doku.php?id=harmony:string_extras )



 What do you think?
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.mozilla.org/pipermail/es-discuss/attachments/20131016/4833e2da/attachment.html>


More information about the es-discuss mailing list