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

前端 未结 6 976
孤城傲影
孤城傲影 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.

    0 讨论(0)
  • 2020-12-05 01:17

    (note: you may skip to the end to find the final ready-to-pick code)


    The one-liner from Blender's answer works great, though I'd favor something more understandable:

    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];
        }
    }
    

    The same using a switch, see how nicer it is to read:

    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];
        }
    }
    

    Of course, these codes can be shortened/optimized, for example by merging the "0", "1" and "2" cases into just the a.join(' and ') from the case "2". I let you tweak these codes according to your taste :)

    Finally, here is my end result, I think it has a great balance between understandability, shortness and efficiency:

    function arrayToText(a) {
        if (a.length <= 2) {
            return a.join(' and ');
        } else {
            return a.slice(0, -1).join(', ') + ' and ' + a[a.length-1];
        }
    }
    
    0 讨论(0)
  • 2020-12-05 01:19
    1. Create comma separated string
    2. Reverse it
    3. Replace first occurrence of " ," with " dna " (" and " backwards)
    4. Reverse it again
    [1, 2, 3]
        .join(', ')
        .split('').reverse().join('')
        .replace(' ,', ' dna ')
        .split('').reverse().join('')
    
    0 讨论(0)
  • 2020-12-05 01:21

    Able to solve it using reduce as well:

    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"
    
    0 讨论(0)
  • 2020-12-05 01:22

    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));
    
    0 讨论(0)
  • 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.
    0 讨论(0)
提交回复
热议问题