数组到逗号分隔的字符串和最后一个标记在jquery中使用'和'而不是逗号 [英] Array to Comma separated string and for last tag use the 'and' instead of comma in jquery

查看:313
本文介绍了数组到逗号分隔的字符串和最后一个标记在jquery中使用'和'而不是逗号的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经用逗号分隔的字符串检查了许多关于连接数组的问题和答案,但我的问题是,我正在使字符串对人类可读,即我有标签数组,如果它们是两个标签,那么它将是 tag1和tag2 如果它们是100个标签,那么它将是 tag1,tag2 ,,,, tag99和tag100 在使用逗号作为分隔符之前使用

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 tags array that's if their is two tags, then it would be tag1 and tag2 and if their is 100 tags then it would be tag1, tag2, ,,,tag99 and tag100 for last one use the and and before using the comma as a separator.

在JQuery中处理任何方法?

Any way to handle in JQuery?

推荐答案

您可以使用 .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(','):获取除最后一个元素之外的所有元素,并用逗号连接它们。

  • a.slice(-1)[0] :这是最后一个元素。

  • .join(a.length< 2?'':'和'):连接该字符串,最后一个元素与连接至少有两个元素。

    • 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.
    • 这篇关于数组到逗号分隔的字符串和最后一个标记在jquery中使用'和'而不是逗号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆