How to split a string into an array based on every FOUR commas?

后端 未结 3 1075
独厮守ぢ
独厮守ぢ 2021-01-06 23:21

so I\'m trying to split a string into an array based on the amount of commas, how do I do that? Say my string is as such;

var string = \"abc, def, ghi, jkl,         


        
3条回答
  •  鱼传尺愫
    2021-01-07 00:12

    split the string at ,. Then create a generic chunk function which splits the array passed into chunks of size specified using Array.from()

    const str = "abc, def, ghi, jkl, mno, pqr, stu, vwx, yza",
          splits = str.split(/,\s*/),
          chunk = (arr, size) => Array.from({ length: Math.ceil(arr.length / size) },
                                  (_, i) => arr.slice(i * size, (i + 1) * size))
    
    console.log(JSON.stringify(chunk(splits, 4)))
    console.log(JSON.stringify(chunk(splits, 3)))

提交回复
热议问题