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

后端 未结 8 1527
耶瑟儿~
耶瑟儿~ 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:50

    const theString = "a=b=c=d";
    const [first, ...rest] = theString.split("=");
    const second = rest.join("=")
    console.log(first, second)

    If you are using ECMA 2015, you just need 2 lines.

    0 讨论(0)
  • 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.

    0 讨论(0)
提交回复
热议问题