In English the rules we use for joining a list of items involves more work than a standard join in JavaScript.
Here is JavaScript code to join an array of elements with commas (,) and an and.
Code
/**
* Join array of strings with commas (,) and "and".
*
* @example input ['one, 'two', 'three'];
* @example return "one, two, and three"
*
* @param {string[]} array of strings.
* @return {string} string created by joining the
* array with commas and "and".
*/
function addCommasAndAnd(list) {
if (list.length < 3) { return list.join(' and '); }
return `${list.slice(0, - 1).join(', ')}, and ${list[list.length - 1]}`;
};
Thank You
Thank you to Mike England for his help crafting this solution.
Future Solution
The browser native Intl.ListFormat will perform exactly this sort of joining with commas (,) and and however at the time of this writing browser support is limited.
If you want to plan for the future, you can use this functionality with a polyfill.
Leave a Reply