Limiting the times that .split() splits, rather than truncating the resulting array

后端 未结 8 1532
耶瑟儿~
耶瑟儿~ 2020-12-11 01:58

Really, pretty much what the title says.

Say you have this string:

var theString = \"a=b=c=d\";

Now, when you run theString

8条回答
  •  旧巷少年郎
    2020-12-11 02:59

    This my implementation:

    String.prototype.splitRemainder = function(delim, count) {
    	if (typeof delim !== 'string') {
    		return this.split();    
    	}
    
    	if (typeof count !== 'number') {
    		return this.split(delim);
    	}
    
    	if (count < 2) {
    		return this.split(delim);
    	}
    
    	count--;
    	const parts = this.split(delim, count);
    	const remainder = this.slice(parts.join('').length + count);
    
    	if (remainder.length > 0) {
    		parts.push(remainder);
    	}
    
    	return parts;
    }
    
    console.log("dasd asds asds asdasd asdasdas".splitRemainder(" ", 4));
    console.log("hello-to-you-too".splitRemainder("-",2));

    Note that it is not the most efficient way to implement it. So if you're looking for the most efficient solution this is not it.

提交回复
热议问题