Array to Comma separated string and for last tag use the 'and' instead of comma in jquery

You can use .slice():

> var a = [1, 2, 3, 4, 5];
> [a.slice(0, -1).join(', '), a.slice(-1)[0]].join(a.length < 2 ? '' : ' and ');
'1, 2, 3, 4 and 5'
  • a.slice(0, -1).join(', '): takes all but the last element and joins them together with a comma.
  • a.slice(-1)[0]: it's the last element.
  • .join(a.length < 2 ? '' : ' and '): joins that string and the last element with and if there are at least two elements.

Another quick solution is to replace the last comma with and.

The following code:

var a = [0,1,2,3,4];
a.join(', ').replace(/,(?!.*,)/gmi, ' and');

should do the trick. (Also, play with the regex modifiers to your need).

One probable issue might be of time when you have large array, but it should work.


Try this:

    var substr = new Array("One", "Two", "Three");
    var commaList = '';

    var i;
    for (i = 0; i < substr.length; ++i) {
        if (i == substr.length - 1)
            commaList += " and " + substr[i];
        else
            commaList += ", " + substr[i];
    }

    console.debug(commaList.substr(2, commaList.length));