split is behind almost every bit of text parsing in the browser: reading a CSV line, a query string, a path, a list of tags typed with commas. Its rules for the odd cases are precise and surprising: "".split(",") is [""] but "".split("") is [], a separator at the end leaves an empty piece, and a limit of -1 means "no limit". Rebuilding it shows each of those rules.
Write split(text, separator, limit) in split.js. It behaves like text.split(separator, limit) when separator is not a regular expression.
Returns the pieces of text between occurrences of separator, in order. A separator of several characters works, and is plain text: ., * and + have no special meaning.
Empty pieces are kept: before a separator at the start, after one at the end, and between two separators next to each other.
Matches do not overlap: after a match, the search continues from its end. split("aaa", "aa") is ["", "a"].
When the separator is not found, the result is [text]; an empty text gives [""].
An empty separator splits text into its UTF-16 code units, as the built-in does (an emoji gives two pieces); an empty text then gives [].
An undefined separator (or none) returns [text].
limit is the most pieces to return. undefined means no limit. Any other value is converted the way the built-in converts it: to an unsigned 32-bit integer, so 2.7 is 2, "2" is 2, -1 is 4294967295, and NaN and null are 0.
A limit of 0 returns [], whatever the separator.
separator and text are converted with String: split(12321, 2) is ["1", "3", "1"].
Every call returns a new array, and a text of 20,000 pieces is split quickly.