This is my version for regexp delimiters. It has same interface with String.prototype.split; it will treat global and non global regexp with no difference. Returned value is an array that odd member of it are matched delimiters.
function split(text, regex) {
var token, index, result = [];
while (text !== '') {
regex.lastIndex = 0;
token = regex.exec(text);
if (token === null) {
break;
}
index = token.index;
if (token[0].length === 0) {
index = 1;
}
result.push(text.substr(0, index));
result.push(token[0]);
index = index + token[0].length;
text = text.slice(index);
}
result.push(text);
return result;
}
// Tests
assertEquals(split("abcdeabcde", /d/), ["abc", "d", "eabc", "d", "e"]);
assertEquals(split("abcdeabcde", /d/g), ["abc", "d", "eabc", "d", "e"]);
assertEquals(split("1.2,3...4,5", /[,\.]/), ["1", ".", "2", ",", "3", ".", "", ".", "", ".", "4", ",", "5"]);
assertEquals(split("1.2,3...4,5", /[,\.]+/), ["1", ".", "2", ",", "3", "...", "4", ",", "5"]);
assertEquals(split("1.2,3...4,5", /[,\.]*/), ["1", "", "", ".", "2", "", "", ",", "3", "", "", "...", "4", "", "", ",", "5", "", ""]);
assertEquals(split("1.2,3...4,5", /[,\.]/g), ["1", ".", "2", ",", "3", ".", "", ".", "", ".", "4", ",", "5"]);
assertEquals(split("1.2,3...4,5", /[,\.]+/g), ["1", ".", "2", ",", "3", "...", "4", ",", "5"]);
assertEquals(split("1.2,3...4,5", /[,\.]*/g), ["1", "", "", ".", "2", "", "", ",", "3", "", "", "...", "4", "", "", ",", "5", "", ""]);
assertEquals(split("1.2,3...4,5.", /[,\.]/), ["1", ".", "2", ",", "3", ".", "", ".", "", ".", "4", ",", "5", ".", ""]);
assertEquals(split("1.2,3...4,5.", /[,\.]+/), ["1", ".", "2", ",", "3", "...", "4", ",", "5", ".", ""]);
assertEquals(split("1.2,3...4,5.", /[,\.]*/), ["1", "", "", ".", "2", "", "", ",", "3", "", "", "...", "4", "", "", ",", "5", "", "", ".", ""]);
assertEquals(split("1.2,3...4,5.", /[,\.]/g), ["1", ".", "2", ",", "3", ".", "", ".", "", ".", "4", ",", "5", ".", ""]);
assertEquals(split("1.2,3...4,5.", /[,\.]+/g), ["1", ".", "2", ",", "3", "...", "4", ",", "5", ".", ""]);
assertEquals(split("1.2,3...4,5.", /[,\.]*/g), ["1", "", "", ".", "2", "", "", ",", "3", "", "", "...", "4", "", "", ",", "5", "", "", ".", ""]);
// quick and dirty assert check
function assertEquals(actual, expected) {
console.log(JSON.stringify(actual) === JSON.stringify(expected));
}