[removed] nice human readable join of list

前端 未结 7 1822
半阙折子戏
半阙折子戏 2021-01-26 10:11

Having a list (array) of tags [\'tag1\', \'tag2\', \'tag3\'] I want to generate a nice title like: Content tagged tag1, tag2 and tag3.

For the

7条回答
  •  耶瑟儿~
    2021-01-26 10:17

    You could get the two last elements and join them with ' and ' and put it as last element back into the array and later join all elements with ', ' for getting a nice string.

    Methods

    • Array#concat, joins two arrays and returns a new array

    • Array#splice, for getting the last two elemensts of the array

    • Array#join, joins an array with the given spacer.

    This proposal works for any length of an array, even with one or two elements.

    function nice([...array]) {
        return array.concat(array.splice(-2, 2).join(' and ')).join(', ');
    }
    
    console.log("Content tagged " + nice(['tag1']));
    console.log("Content tagged " + nice(['tag1', 'tag2']));
    console.log("Content tagged " + nice(['tag1', 'tag2', 'tag3']));

提交回复
热议问题