admin管理员组文章数量:1391951
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.
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.
Share Improve this question asked Sep 29, 2017 at 17:48 Haider AliHaider Ali 9642 gold badges12 silver badges27 bronze badges 4- Don't try to split, try to match at least 3 lines. – Casimir et Hippolyte Commented Sep 29, 2017 at 17:49
- @CasimiretHippolyte Not quite sure how to do that, i've found patterns that match multiple lines, having trouble finding patterns that match every n number of lines. – Haider Ali Commented Sep 29, 2017 at 17:52
-
1
@HaiderAli In this case, How do you want your output to be when your input is
One\n\n\n\n\nTwo\n\nThree\n\nFour\n\nFive\n\n\n\nSix\n
? – Gurmanjot Singh Commented Sep 29, 2017 at 18:03 - @Gurman That will not occur, the string is programatically prepared from an array. I'd rather split a string rather paginate an array ;p – Haider Ali Commented Sep 29, 2017 at 18:12
2 Answers
Reset to default 4Instead 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;
}, []);
Straight-forward:
(?:.+\n?){3}
See a demo on regex101..
Broken down, this says:
(?: # open non-capturing group
.+ # the whole line
\n? # a newline character, eventually but greedy
){3} # repeat the group three times
本文标签: regexSplit string at every nth linebreak using javascriptStack Overflow
版权声明:本文标题:regex - Split string at every nth linebreak using javascript - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1744722680a2621789.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论