Having a list (array) of tags [\'tag1\', \'tag2\', \'tag3\']
I want to generate a nice title like: Content tagged tag1, tag2 and tag3
.
For the
You could get the two last elements and join them with ' and '
and put it as last element back into the array and later join all elements with ', '
for getting a nice string.
Methods
Array#concat, joins two arrays and returns a new array
Array#splice, for getting the last two elemensts of the array
Array#join, joins an array with the given spacer.
This proposal works for any length of an array, even with one or two elements.
function nice([...array]) {
return array.concat(array.splice(-2, 2).join(' and ')).join(', ');
}
console.log("Content tagged " + nice(['tag1']));
console.log("Content tagged " + nice(['tag1', 'tag2']));
console.log("Content tagged " + nice(['tag1', 'tag2', 'tag3']));