[removed] nice human readable join of list

前端 未结 7 1680
半阙折子戏
半阙折子戏 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:14

    A bit of slicing and dicing using Array.prototype.slice:

    function naturalLanguageJoin(arr){
        if(!arr)
           return '';
        if(arr.length<2)
           return (arr.length>0) ? arr[0] : '';
        return arr.slice(0,arr.length-1).join(", ") + " and " + arr[arr.length-1];
    }
    
    console.log(naturalLanguageJoin(['tag1', 'tag2', 'tag3']));
    console.log(naturalLanguageJoin(['tag1', 'tag2']));
    console.log(naturalLanguageJoin(['tag1']));
    console.log(naturalLanguageJoin([]));
    console.log(naturalLanguageJoin(null));

提交回复
热议问题