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
Yet another implementation I just wrote:
export function split(subject, separator, limit=undefined, pad=undefined) {
if(!limit) {
return subject.split(separator);
}
if(limit < 0) {
throw new Error(`limit must be non-negative`);
}
let result = [];
let fromIndex = 0;
for(let i=1; i
Doesn't use regexes, nor does it over-split and re-join.
This version guarantees exactly limit
elements (will pad with undefined
s if there aren't enough separators); this makes it safe to do this kind of ES6 stuff:
let [a,b,c] = split('a$b','$',3,null);
// a = 'a', b = 'b', c = null