searchingSO
searchingSO

Reputation: 79

Javascript split a long file stored in a string into an array of strings based on tthe number of lines

I have looked up other solutions but none of them fit my requirement.

Lets say I have a long file with the following data in a var str:

Lorem Ipsum is simply dummy text of the printing and typesetting industry.
Lorem Ipsum is simply dummy text of the printing and typesetting industry.
Lorem Ipsum is simply dummy text of the printing and typesetting industry.

Lorem Ipsum is simply dummy text of the printing and typesetting industry.
Lorem Ipsum is simply dummy text of the printing and typesetting industry.
Lorem Ipsum is simply dummy text of the printing and typesetting industry.

Lorem Ipsum is simply dummy text of the printing and typesetting industry.
Lorem Ipsum is simply dummy text of the printing and typesetting industry.
Lorem Ipsum is simply dummy text of the printing and typesetting industry.

I want it to be broken into an array of 3 strings based on new line. So new array, say var strSplit has strSplit[0]:

Lorem Ipsum is simply dummy text of the printing and typesetting industry.
Lorem Ipsum is simply dummy text of the printing and typesetting industry.
Lorem Ipsum is simply dummy text of the printing and typesetting industry.

I want str to be split based on the blank line after each section of text. I am unable to figure it out.

Upvotes: 0

Views: 92

Answers (1)

Karan
Karan

Reputation: 12629

You can split your string with str.split(/\r?\n\r?\n/);. Check it below.

var str = `Lorem Ipsum is simply dummy text of the printing and typesetting industry.
Lorem Ipsum is simply dummy text of the printing and typesetting industry.
Lorem Ipsum is simply dummy text of the printing and typesetting industry.

Lorem Ipsum is simply dummy text of the printing and typesetting industry.
Lorem Ipsum is simply dummy text of the printing and typesetting industry.
Lorem Ipsum is simply dummy text of the printing and typesetting industry.

Lorem Ipsum is simply dummy text of the printing and typesetting industry.
Lorem Ipsum is simply dummy text of the printing and typesetting industry.
Lorem Ipsum is simply dummy text of the printing and typesetting industry.`;

var result = str.split(/\r?\n\r?\n/);
console.log(result.length)

Upvotes: 1

Related Questions