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
Although you can give split a limit, you won't get back what you've said you want. Unfortunately, you will have to roll your own on this, e.g.:
var string = 'Split this, but not this';
var result = string.split(' ');
if (result.length > 3) {
result[2] = result.slice(2).join(' ');
result.length = 3;
}
But even then, you end up modifying the number of spaces in the latter parts of it. So I'd probably just do it the old-fashioned write-your-own-loop way:
function splitWithLimit(str, delim, limit) {
var index,
lastIndex = 0,
rv = [];
while (--limit && (index = str.indexOf(delim, lastIndex)) >= 0) {
rv.push(str.substring(lastIndex, index));
lastIndex = index + delim.length;
}
if (lastIndex < str.length) {
rv.push(str.substring(lastIndex));
}
return rv;
}
Live copy