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

后端 未结 18 962
有刺的猬
有刺的猬 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 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+.

提交回复
热议问题