使用 javascript 在每第 n 个换行符处分割字符串

Hai*_*Ali 8 javascript regex split

我正在寻找一种在每第 n 个换行符处分割字符串的解决方案。假设我有一个有六行的字符串

"One\nTwo\nThree\nFour\nFive\nSix\n"
Run Code Online (Sandbox Code Playgroud)

所以在第三行中断处分割会给我类似的东西

"One\nTwo\nThree\n" and "Four\nFive\nSix\n"
Run Code Online (Sandbox Code Playgroud)

我已经找到了在第 n 个字符处执行此操作的解决方案,但我无法确定第 n 个字符的长度会发生中断。我希望我的问题很清楚。谢谢。

Cas*_*yte 4

不使用String.prototype.split,使用String.prototype.match方法更容易:

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

演示

图案细节:

(?=[\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)
Run Code Online (Sandbox Code Playgroud)

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;
}, []);
Run Code Online (Sandbox Code Playgroud)