I\'d like to split a string only the at the first n occurrences of a delimiter. I know, I could add them together using a loop, but isn\'t there a more straight forward appr
Hi there i had the same problem wanted to split only several times, couldnt find anything so i just extended the DOM - just a quick and dirty solution but it works :)
String.prototype.split = function(seperator,limit) {
var value = "";
var hops = [];
// Validate limit
limit = typeof(limit)==='number'?limit:0;
// Join back given value
for ( var i = 0; i < this.length; i++ ) { value += this[i]; }
// Walkthrough given hops
for ( var i = 0; i < limit; i++ ) {
var pos = value.indexOf(seperator);
if ( pos != -1 ) {
hops.push(value.slice(0,pos));
value = value.slice(pos + seperator.length,value.length)
// Done here break dat
} else {
break;
}
}
// Add non processed rest and return
hops.push(value)
return hops;
}
In your case would look like that
>>> "Split this, but not this".split(' ',2)
["Split", "this,", "but not this"]