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
A bit of slicing and dicing using Array.prototype.slice
:
function naturalLanguageJoin(arr){
if(!arr)
return '';
if(arr.length<2)
return (arr.length>0) ? arr[0] : '';
return arr.slice(0,arr.length-1).join(", ") + " and " + arr[arr.length-1];
}
console.log(naturalLanguageJoin(['tag1', 'tag2', 'tag3']));
console.log(naturalLanguageJoin(['tag1', 'tag2']));
console.log(naturalLanguageJoin(['tag1']));
console.log(naturalLanguageJoin([]));
console.log(naturalLanguageJoin(null));