What I want is something like Array.join(separator)
, but which takes a second argument Array.join(separator, beforeLastElement)
, so when I say [f
Array.prototype.join2 = function(all, last) {
var arr = this.slice(); //make a copy so we don't mess with the original
var lastItem = arr.splice(-1); //strip out the last element
arr = arr.length ? [arr.join(all)] : []; //make an array with the non-last elements joined with our 'all' string, or make an empty array
arr.push(lastItem); //add last item back so we should have ["some string with first stuff split by 'all'", last item]; or we'll just have [lastItem] if there was only one item, or we'll have [] if there was nothing in the original array
return arr.join(last); //now we join the array with 'last'
}
> [1,2,3,4].join2(', ', ' and ');
>> "1, 2, 3 and 4"