How to split string by empty line in javascript

Viewed 5157

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.

2 Answers

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.map((data) => data.split("\n"));
Related