Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Split string at every nth linebreak using javascript

I'm looking for a solution to split a string at every nth linebreak. Lets say i have one string that has six lines

"One\nTwo\nThree\nFour\nFive\nSix\n"

So splitting at 3rd line break would give me something like

"One\nTwo\nThree\n" and "Four\nFive\nSix\n"

I've found solutions to do it at nth character, but i can't be definite of at what character length the nth break would occur. I hope my question is clear. Thanks.

like image 327
Haider Ali Avatar asked Jun 27 '26 20:06

Haider Ali


2 Answers

Instead of using the String.prototype.split, it's easier to use the String.prototype.match method:

"One\nTwo\nThree\nFour\nFive\nSix\n".match(/(?=[\s\S])(?:.*\n?){1,3}/g);

demo

pattern details:

(?=[\s\S]) # ensure there's at least one character (avoid a last empty match)

(?:.*\n?)  # a line (note that the newline is optional to allow the last line)

{1,3} # greedy quantifier between 1 and 3
      # (useful if the number of lines isn't a multiple of 3)

Other way with Array.prototype.reduce:

"One\nTwo\nThree\nFour\nFive\nSix\n".split(/^/m).reduce((a, c, i) => {
    i%3  ?  a[a.length - 1] += c  :  a.push(c);
    return a;
}, []);
like image 183
Casimir et Hippolyte Avatar answered Jun 30 '26 10:06

Casimir et Hippolyte


Straight-forward:

(?:.+\n?){3}

See a demo on regex101.com.


Broken down, this says:
(?:  # open non-capturing group
.+   # the whole line
\n?  # a newline character, eventually but greedy
){3} # repeat the group three times
like image 36
Jan Avatar answered Jun 30 '26 10:06

Jan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!