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 with limit;
// takes string input only
function split(input, separator, limit) {
input = input.split(separator);
if (limit) {
input = input.slice(0, limit - 1).concat(input.slice(limit - 1).join(separator));
}
return input;
}
In my case this solves my problem:
const splitted = path.split('/')
const core = splittedPath.slice(0, 2)
const rest = splittedPath.slice(2).join('/')
const result = [...core, rest]
const splitAndAppend = (str, delim, count) => {
const arr = str.split(delim);
return [...arr.splice(0, count), arr.join(delim)];
}
Complexity O(n).
In my case I was trying to parse git grep stdout. So I had a {filename}:{linenumber}:{context}. I don't like splitting and then joining. We should be able to parse the string one time. You could simply step through each letter and split on the first two colons. A quicker way to do it out of the box is by using the match method and regex.
Hence,
txt.match(/(.+):(\d+):(.*)/)
Works great
Improved version of a sane limit
implementation with proper RegEx support:
function splitWithTail(value, separator, limit) {
var pattern, startIndex, m, parts = [];
if(!limit) {
return value.split(separator);
}
if(separator instanceof RegExp) {
pattern = new RegExp(separator.source, 'g' + (separator.ignoreCase ? 'i' : '') + (separator.multiline ? 'm' : ''));
} else {
pattern = new RegExp(separator.replace(/([.*+?^${}()|\[\]\/\\])/g, '\\$1'), 'g');
}
do {
startIndex = pattern.lastIndex;
if(m = pattern.exec(value)) {
parts.push(value.substr(startIndex, m.index - startIndex));
}
} while(m && parts.length < limit - 1);
parts.push(value.substr(pattern.lastIndex));
return parts;
}
Usage example:
splitWithTail("foo, bar, baz", /,\s+/, 2); // -> ["foo", "bar, baz"]
Built for & tested in Chrome, Firefox, Safari, IE8+.
var result = [string.split(' ',1).toString(), string.split(' ').slice(1).join(' ')];
Results in:
["Split", "this, but not this"]