[英]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.