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

前端 未结 6 988
孤城傲影
孤城傲影 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:08

    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.

提交回复
热议问题