Are you looking for something closer to PHP explode ?
Here is the method I developed:
String.prototype.explode = function(sep, n) { var arr = this.split(sep, n) if (arr[n-1] != undefined) arr[n-1] += this.substring(arr.join(' ').length); return arr; }
This method breaks the line, as usual, determines whether our limit is successful and uses substring to add text beyond the limits of our last partition (we can directly access the offset of the first character after the last section, getting the length of join used in an array with any single symbol as a separator)
This method is used the same way as split :
str = 'my/uri/needs/to/be/split'; splitResult = str.split('/', 4); explodeResult = str.explode('/', 4); console.log(splitResult); console.log(explodeResult); // The following will be written to the console: // splitResult: ["my", "uri", "needs", "to"] // explodeResult: ["my", "uri", "needs", "to/be/split"]
And of course, this can also be minimized as a function:
function explode(str, sep, n) { var arr = str.split(sep, n) if (arr[n-1] != undefined) arr[n-1] += this.substring(arr.join(' ').length); return arr; } str = 'my/uri/needs/to/be/split'; explodeResult = explode(str, '/', 4);
source share