[英]Split 2 or more new lines into sentences using JavaScript?
我想在 JavaScript 中拆分 2 个或更多新行。
例如,
Hello
\n
Don't split me
\n
\n
But split me since I am 2 or more lines below
\n
\n
\n
\n
\n
\n
You can also split me since I am 6 lines below
应该导致
Hello
Don't split me
But split me since I am 2 or more lines below
You can also split me since I am 6 lines below
基本上删除所有\\n
。
我尝试做str.split(/\\r?\\n/)
但它拆分为单行。 我希望它可以用于 2 行或更多行,但它必须适用于 CR、LF 和 CRLF 行尾。
我确实看到了https://stackoverflow.com/a/52947649/6141587但它也只适用于单行。 从字面上看,每个答案都是针对我知道该怎么做的单行换行符。
我希望它适用于 2 个或更多新行。
我该怎么做?
我会充分利用 JavaScript 字符串方法split()
和trim()
和一些基本的正则表达式:
const input =
"Hello\nDon't split me\n\nBut split me since I am 2 or more lines below\n\n\n\n\n\nYou can also split me since I am 6 lines below";
const re = new RegExp(/(\n){2,}|(\r\n){2,}|(\r){2,}/);
const output = input.split(re);
for (let i = 0; i < output.length; i++) {
output[i] = output[i].trim();
}
console.log(output);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.