Skip to content Skip to sidebar Skip to footer

How To Split A String Into An Array Based On Every Four Commas?

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, mno, pqr, stu, vwx, yza'

Solution 1:

I'd use .match instead of split - match (non commas, followed by a comma or the end of the string) 4 times:

var string = "abc, def, ghi, jkl, mno, pqr, stu, vwx, yza";
const result = string.match(/(?:[^,]+(?:,|$)){1,4}/g);
console.log(result);
  • (?:[^,]+(?:,|$)){1,4} - Repeat, 1 to 4 times:
    • [^,]+ - Non comma characters
    • (?:,|$) - Either a comma, or the end of the string

If you want to make sure the first character is not whitespace, lookahead for \S (a non-whitespace character) at the beginning:

var string = "abc, def, ghi, jkl, mno, pqr, stu, vwx, yza";
const result = string.match(/(?=\S)(?:[^,]+(?:,|$)){1,4}/g);
console.log(result);

Solution 2:

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)))

Solution 3:

You can use split and reduce also to achieve this :

let array = str.split(", ").reduce((prev, curr, i) => {
      if(i%4 === 0){
         prev.push([]);
      }
      prev[prev.length - 1].push(curr);
      return prev;
   }, [])

Post a Comment for "How To Split A String Into An Array Based On Every Four Commas?"