Skip to content

Instantly share code, notes, and snippets.

@Yaffle
Created March 16, 2012 12:34
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Yaffle/2049878 to your computer and use it in GitHub Desktop.
Save Yaffle/2049878 to your computer and use it in GitHub Desktop.
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
Copy link

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