简体   繁体   中英

How to split string by empty line in javascript

I have string loaded from file:

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

variable data is:

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"); and 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.

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"); }) ;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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