拆分字符串值但将换行符保留在新数组中

split string value but keep the line break inside new array

我想在对文本区域元素的字符串值执行一些逻辑后保留换行符。可以说我的文本区域有这个字符串:

"Test

Newline here"

数组:["Test\nNewline", "here"]

如何保存成这样:["Test", "\n", "Newline", "here"]

我的代码:

let bodyText = "Test

Newline here"

let bodyTextArray = bodyText.split(/ |\n|(?=\n)/g)

基本上发生的事情是拆分和删除空格和“\n”。使用正面前瞻不起作用,我尝试使用负面前瞻但没有成功。

有什么想法吗?

你可以匹配那些:

let bodyText = `Test

Newline here`
let bodyTextArray = bodyText.match(/^\n|\S+/gm)
console.log(bodyTextArray)

详情:

  • ^\n - 行首和换行符
  • | - 或
  • \S+ - 任何一个或多个非空白字符。

要支持 CRLF、LF 或 CR 行结尾,请使用

/^(?:\r\n?|\n)|\S+/gm

其中 (?:\r\n?|\n) 替换了 \n 并匹配 CR 和可选的 LF 字符,或仅匹配 LF 字符。

你需要这个

let bodyText = "Test
Newline here"
let bodyTextArray = bodyText.split(/( |\n)/)

如果您将捕获 () 放在要拆分的内容周围,那么它将被添加到输出中

您可以使用此正则表达式进行拆分:

/(\n)+|\s+/

代码:

const input = `Test

Newline here`;

var arr = input.split(/(\n)+|\s+/);

console.log(arr.filter(Boolean));

解释:

  • /(\n)+|\s+/ 在捕获单个换行符时在 1+ 个换行符上拆分输入(以使 \n 在拆分后在输出数组中可用)或 1+ 个空格
  • .filter(Boolean) 从数组
  • 中删除空的或未定义的条目