8

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
  • Have you tried with data.split("\n\n"); ? Commented Oct 3, 2017 at 18:33
  • Not working correctly. Added some special characters after each string. See: (2) ["1↵2↵3", "a↵b↵c↵d↵e"] - tested in chrome console. Commented Oct 3, 2017 at 18:34

2 Answers 2

11

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.

Sign up to request clarification or add additional context in comments.

1 Comment

you may want to append .filter(x=>x.length > 0) at the end of the incantation to account for whitespace at the start or the end of the string.
6

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.