【问题标题】:Split 2 or more new lines into sentences using JavaScript?使用 JavaScript 将 2 个或更多新行拆分为句子?
【发布时间】:2021-07-20 14:19:39
【问题描述】:

我想在 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

应该会导致

1

Hello

Don't split me

2

But split me since I am 2 or more lines below

3

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 个或更多新行。

我该怎么做?

【问题讨论】:

  • 你试过什么?你在哪里卡住?编辑您的问题以包含您迄今为止编写的代码以满足此要求(作为minimal reproducible example)以及对您遇到具体的位置的说明(包括所有错误消息和其他相关调试信息)按照How to Ask.
  • 你最好的选择是做你的研究,search 以获取有关 SO 的相关主题,然后试一试。 如果您在进行更多研究和搜索后遇到困难并且无法摆脱困境,请发布您的尝试minimal reproducible example,并具体说明您遇到的问题。人们会很乐意提供帮助。 (不是我的反对票)
  • @esqew & TJ 添加了描述:)

标签: javascript regex


【解决方案1】:

我会通过一些基本的正则表达式充分利用 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);

【讨论】:

  • 你可以编辑它来为CR, LF, and CRLF line endings工作吗?
  • 好的,刚刚编辑。将在 2+ '\n' 或 2+ '\r\n' 或 2+ '\r' 上拆分。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-12-29
  • 2018-01-15
  • 1970-01-01
  • 2018-10-12
  • 2017-11-20
  • 2022-01-10
相关资源
最近更新 更多