-1

I want to split 2 or more new lines in JavaScript.

For example,

Hello
\n
Don't split me
\n
\n
But split me since I am 2 or more lines below
\n
\n
\n
\n
\n
\n
You can also split me since I am 6 lines below

should result in

1

Hello

Don't split me

2

But split me since I am 2 or more lines below

3

You can also split me since I am 6 lines below

Basically removing all \n.

I tried doing str.split(/\r?\n/) but it splits for single-line. I want it to do for 2 or more lines but it must work for CR, LF, and CRLF line endings.

I did see https://stackoverflow.com/a/52947649/6141587 but it only does for single-line as well. Literally, every answer is for a single-line break which I know how to do.

I want it to work for 2 or more new lines.

How do I do it?

deadcoder0904
  • 7,232
  • 12
  • 66
  • 163
  • What have you tried? Where are you getting stuck? Edit your question to include the code you've written so far to meet this requirement (as a [mre]) along with an explanation of where *specifically* you're getting stuck (including all error messages and other pertinent debugging information) in accordance with [ask]. – esqew Jul 20 '21 at 14:21
  • Your best bet here is to do your research, [search](/help/searching) for related topics on SO, and give it a go. ***If*** you get stuck and can't get unstuck after doing more research and searching, post a [mcve] of your attempt and say specifically where you're stuck. People will be glad to help. *(not my downvote)* – T.J. Crowder Jul 20 '21 at 14:22
  • @esqew & TJ added a description :) – deadcoder0904 Jul 20 '21 at 15:10

1 Answers1

1

I would take full advantage of JavaScript String methods split() and trim() with some basic Regex:

const input =
"Hello\nDon't split me\n\nBut split me since I am 2 or more lines below\n\n\n\n\n\nYou can also split me since I am 6 lines below";

const re = new RegExp(/(\n){2,}|(\r\n){2,}|(\r){2,}/);
const output = input.split(re);

for (let i = 0; i < output.length; i++) {
    output[i] = output[i].trim();
}
console.log(output);
Shaan K
  • 356
  • 1
  • 7