使用javascript在每隔n个换行符处拆分字符串
问题描述:
我正在寻找解决方案,以在每第n个换行符处拆分字符串。 可以说我有一个具有六行使用javascript在每隔n个换行符处拆分字符串
"One\nTwo\nThree\nFour\nFive\nSix\n"
因此,在3号线突破分裂会给我像
"One\nTwo\nThree\n" and "Four\nFive\nSix\n"
一个字符串,我已经找到解决方案,在第n个字符做,但我不能确定第n次中断会发生在什么字符长度上。 我希望我的问题很清楚。 谢谢。
答
除了使用String.prototype.split的,它更容易使用String.prototype.match方法:
"One\nTwo\nThree\nFour\nFive\nSix\n".match(/(?=[\s\S])(?:.*\n?){1,3}/g);
图案的详细资料:
(?=[\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)
与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;
}, []);
答
看,此说:
直接:
(?:.+\n?){3}
看,此说:
(?: # open non-capturing group
.+ # the whole line
\n? # a newline character, eventually but greedy
){3} # repeat the group three times
不要试图分裂,尝试匹配至少3行。 –
@CasimiretHippolyte不太清楚如何做到这一点,我发现匹配多行的模式,无法找到匹配每n行的模式。 –
@HaiderAli在这种情况下,您希望您的输出在您的输入为'One \ n \ n \ n \ n \ nTwo \ n \ nThree \ n \ nFour \ n \ nFive \ n \ n \ n \ nSix \ N'? – Gurman