Split a string only the at the first n occurrences of a delimiter

后端 未结 18 810
有刺的猬
有刺的猬 2020-12-24 06:22

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

相关标签:
18条回答
  • 2020-12-24 06:56

    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;
    }
    
    0 讨论(0)
  • 2020-12-24 06:56

    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]
    
    0 讨论(0)
  • 2020-12-24 06:57

    ES2015

    const splitAndAppend = (str, delim, count) => {
        const arr = str.split(delim);
        return [...arr.splice(0, count), arr.join(delim)];
    }
    

    Complexity O(n).

    0 讨论(0)
  • 2020-12-24 06:57

    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

    0 讨论(0)
  • 2020-12-24 07:01

    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+.

    0 讨论(0)
  • 2020-12-24 07:02
    var result = [string.split(' ',1).toString(), string.split(' ').slice(1).join(' ')];
    

    Results in:

    ["Split", "this, but not this"]
    
    0 讨论(0)
提交回复
热议问题