JS regex for line split

How do you split a long piece of text into separate lines? Why does this return string1 twice?

/^(.*?)$/mg.exec('line1\r\nline2\r\n'); 

["line1", "line1"]

I turned on the multi-line modifier to make ^ and $ match the beginning and end of the lines. I also included a global modifier to capture all lines.

I want to use regex separation, not String.split , because I will deal with Linux \n and Windows \r\n line endings.

+47
javascript regex newline
Feb 17 2018-11-21T00:
source share
6 answers
 arrayOfLines = lineString.match(/[^\r\n]+/g); 

As Tim said, this is both a full match and a takeover. It appears that regex.exec(string) returns to search for the first match regardless of the global modifier if string.match(regex) performs a global check.

+85
Feb 17 '11 at 21:44
source share
β€” -

Using

 result = subject.split(/\r?\n/); 

Your regular expression returns line1 twice, because line1 is both a complete match and the contents of the first capture group.

+73
Feb 17 '11 at 9:40 a.m.
source share

I assume the following characters are newlines

  • \ r followed by \ n
  • \ n followed by \ r
  • \ n is present separately
  • \ r is present separately

Use

 var re=/\r\n|\n\r|\n|\r/g; arrayofLines=lineString.replace(re,"\n").split("\n"); 

for an array of all rows, including empty ones.

OR

Use

 arrayOfLines = lineString.match(/[^\r\n]+/g); 

For an array of non-empty strings

+18
Aug 29 '13 at 16:11
source share

An even simpler regular expression that processes all combinations of lines, even mixed in one file, and also removes empty lines:

var lines = text.split(/[\r\n]+/g);

With spaces:

var lines = text.trim().split(/\s*[\r\n]+\s*/g);

+12
Apr 21 '15 at 17:11
source share

First replace all \r\n with \n , then String.split .

+6
Feb 17 2018-11-21 at
source share

http://jsfiddle.net/uq55en5o/

var lines = text.match(/^.*((\r\n|\n|\r)|$)/gm);

I did something like this. Above the link is my violin.

0
Jan 12 '15 at 13:01
source share



All Articles