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

前端 未结 6 987
孤城傲影
孤城傲影 2020-12-05 00:55

I have checked many questions and answers regarding join array with comma separated string, But my problem is that, I am making the string readable for human i.e I have tag

6条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-12-05 01:27

    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.

提交回复
热议问题