数组以逗号分隔字符串,最后一个标记使用'and'而不是jquery中的逗号

pw9qyyiw  于 2023-06-05  发布在  jQuery
关注(0)|答案(9)|浏览(379)

我已经检查了许多问题和答案关于连接数组逗号分隔字符串,但我的问题是,我使字符串可读的人,即我有标签数组,如果他们是两个标签,那么它将是tag1 and tag2,如果他们是100标签,那么它将是tag1, tag2, ,,,tag99 and tag100最后一个使用and和之前使用逗号作为分隔符.
如何在jQuery中处理?

v64noz0r

v64noz0r1#

可以使用.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 ? '' : ' and '):如果至少有两个元素,则用and连接该字符串和最后一个元素。
vojdkbi0

vojdkbi02#

另一个快速解决方案是用and替换最后一个逗号。
下面的代码:

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

应该可以(另外,根据需要使用regex修饰符)。
一个可能的问题是当你有一个大的数组时,时间可能会很长,但它应该可以工作。

cngwdvgl

cngwdvgl3#

我用regex来做这个。

var words = ['One', 'Two', 'Three'];

var commaWord = words.join(', ');
Output: "One, Two, Three"

var commaAndWord = commaWord.replace(/,([^,]*)$/, ' and$1');
Output: "One, Two and Three"

var singleLine = words.join(', ').replace(/,([^,]*)$/, ' and$1');
Output: "One, Two and Three"
dfuffjeb

dfuffjeb4#

试试这个:

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));
2o7dmzc5

2o7dmzc55#

(note:您可以跳到最后找到最后的准备挑选代码)
Blender的回答中的一行代码很好用,尽管我更喜欢一些更容易理解的东西:

function arrayToText(a) {
    if (a.length === 0) {
        return '';
    } else if (a.length === 1) {
        return String(a[0]); // cast to string, for consistency with the other cases
    } else if (a.length === 2) {
        return a.join(' and ');
    } else {
        return a.slice(0, -1).join(', ') + ' and ' + a[a.length-1];
    }
}

同样的使用开关,看看它是如何更好地阅读:

function arrayToText(a) {
    switch (a.length) {
        case 0:
            return '';
        case 1:
            return String(a[0]); // cast to string, for consistency with the other cases
        case 2:
            return a.join(' and ');
        default:
            return a.slice(0, -1).join(', ') + ' and ' + a[a.length-1];
    }
}

当然,这些代码可以被缩短/优化,例如通过将“0”、“1”和“2”情况合并成来自情况“2”的仅a.join(' and ')。我让你根据你的口味调整这些代码:)
最后,这是我的最终结果,我认为它在可理解性,简短性和效率之间取得了很大的平衡:

function arrayToText(a) {
    if (a.length <= 2) {
        return a.join(' and ');
    } else {
        return a.slice(0, -1).join(', ') + ' and ' + a[a.length-1];
    }
}
vql8enpb

vql8enpb6#

也可以使用reduce来解决:

let items = [1, 2, 3, 4, 5];
items.reduce((acc, curr, i) =>
    i !== 0 ? acc + `${items.length - 1 === i ? ` and  ` : ', '}` + curr : curr, '');
// "1, 2, 3, 4 and  5"
zbsbpyhn

zbsbpyhn7#

编辑:写完这个答案后,我看到one by @diegodsp使用了和我一样的正则表达式,所以我猜我不小心偷了他的答案。好吧!
这个对我来说很好,如果你喜欢,你可以使用牛津逗号。

const formatArray = (arr, oxfordComma = false) => 
  arr.join(", ").replace(/,([^,]+)$/g, `${oxfordComma ? "," : ""} and$1`);

const testArray = ["abc", "def", "efg", "abc abc", "fjdsakfj asd", "jfjfjf jfjfj"];
console.log(formatArray(testArray));
console.log(formatArray(testArray, true));

正则表达式的解释:
,-匹配“,”
([^,]+)-一次或多次捕获除“,”以外的任何字符
$-匹配一行的结尾
替换字符串中的$1表示捕获的单词。

c3frrgcw

c3frrgcw8#

为了解决所有场景,从空的,单个的,两个元素或多个元素,我们可以通过这种方式更有效地使用切片方法:

[...array.slice(0,-2), array.slice(-2).join(' and ')].join(', ')

说明:
它分为三个部分:
1.-...array.slice(0,-2)将处理两个元素以外的所有escenarios。
2.-array.slice(-2).join(' and ')将通过将最后两个元素与“和”连接起来来寻址。
3.前面的部分只有在第一部分有元素的情况下才用.join(', ')连接,否则不会在输出中添加逗号。
用途:
作为内联函数:
((array) => [...array.slice(0,-2), array.slice(-2).join(' and ')].join(', ') )(["apple", "banana", "orange"])
或者作为函数:

function smartJoin(array) { return [...array.slice(0,-2), array.slice(-2).join(' and ')].join(', ') }

/*Unit tests:*/
var array1 = ["apple", "banana", "orange"];
console.log(smartJoin(array1)); // 'apple, banana and orange'
var array2 = ["car", "bike"];
console.log(smartJoin(array2)); // 'car and bike'
var array3 = ["dog", "cat", "bird", "fish"];
console.log(smartJoin(array3)); // 'dog, cat, bird and fish'
var array4 = ["pen"];
console.log(smartJoin(array4)); // 'pen'
var array5 = [];
console.log(smartJoin(array5)); // ''
pgccezyw

pgccezyw9#

您还可以执行以下操作:
1.创建逗号分隔字符串。
1.反转一下。
1.将第一个出现的' ,'替换为' dna '(向后替换'')。
1.再倒过来。

[1, 2, 3]
  .join(', ')
  .split('').reverse().join('')
  .replace(' ,', ' dna ')
  .split('').reverse().join('')

相关问题