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";
How can i split it so that it returns;
var array = ["abc, def, ghi, jkl,", "mno, pqr, stu, vwx,", "yza"]
Is this even possible?
Right now I'm using var array = string.split(', ');
But this adds the strings into the array based on every single comma.
Any help would be appreciated!
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 stringIf 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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With