Skip to content

Instantly share code, notes, and snippets.

@Yaffle Yaffle/gist:2049878
Created Mar 16, 2012

Embed
What would you like to do?
String.prototype.split = function (r, limit) {
var s = String(this),
last = null,
lastIndex = null,
a = [];
limit = (limit === undefined ? -1 : limit) >>> 0;
if (!limit) {
return a;
}
if (r === undefined) {
return [s];
}
if (Object.prototype.toString.call(r) === '[object RegExp]') {
r = new RegExp(r.source, (r.multiline ? 'm' : '') + (r.ignoreCase ? 'i' : '') + 'g');
} else {
r = new RegExp(String(r).replace(/[-[\]{}()*+?.,\\^$|#\s]/g, "\\$&"), 'g');
}
if (s === '') {
return r.test('') ? [] : [''];
}
try {
s.replace(r, function (p) {
function push(x) {
a.push(x);
limit -= 1;
if (!limit) {
throw a;
}
}
var length = arguments.length,
index = arguments[length - 2],
i;
if (lastIndex !== index && !(!p && (last === index || index === 0 || index === s.length))) {
push(s.slice(last || 0, index));
last = index + p.length;
lastIndex = index;
for (i = 1; i < length - 2; i += 1) {
push(arguments[i]);
}
}
});
} catch (e) {
if (e !== a) {
throw e;
}
}
if (lastIndex !== s.length && limit) {
a.push(s.slice(last || 0));
}
return a;
}
@slevithan

This comment has been minimized.

Copy link

slevithan commented Sep 23, 2015

An alternative implementation: https://gist.github.com/slevithan/2048056

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.