简体   繁体   English

如何在JavaScript中用空行分割字符串

[英]How to split string by empty line in javascript

I have string loaded from file: 我从文件中加载了字符串:

var data = load("file.txt");

variable data is: 可变data为:

1
2
3

a
b
c
d
e

How to split this variable into two arrays like this: 怎样将这个变量分成两个数组:

[1, 2, 3]

and

[a, b, c, d, e]

I try data.split("\\n"); 我尝试data.split("\\n"); and data.split("\\r\\n"); data.split("\\r\\n"); but it doesn`t work. 但这不起作用。

Thank for help. 感谢您的帮助。

Try with this: 试试这个:

 var str = `1 2 3 a b c d e` var splitted = str.split(/\\n\\s*\\n/) splitted.forEach((capture, i) => console.log(`Capture #${i}:\\n${capture}`)); 
This code splits the input in the occurrence of 2 carriage returns, optionally filled with any count of spaces. 该代码在出现2个回车符时将输入分割,可以选择填充任意数量的空格。

Since the space represents two line breaks you can try something like this: 由于空格代表两个换行符,因此您可以尝试执行以下操作:

var data = originalData.split("\n\n");

Then one line break: 然后换行:

data.forEach(function(data, index){ data[index] = data.split("\\n"); }) ; data.forEach(function(data, index){ data[index] = data.split("\\n"); }) ;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM