JS regex to split by line
arrayOfLines = lineString.match(/[^\r\n]+/g);
As Tim said, it is both the entire match and capture. It appears regex.exec(string)
returns on finding the first match regardless of global modifier, wheras string.match(regex)
is honouring global.
Use
result = subject.split(/\r?\n/);
Your regex returns line1
twice because line1
is both the entire match and the contents of the first capturing group.
I am assuming following constitute newlines
- \r followed by \n
- \n followed by \r
- \n present alone
- \r present alone
Please Use
var re=/\r\n|\n\r|\n|\r/g;arrayofLines=lineString.replace(re,"\n").split("\n");
for an array of all Lines including the empty ones.
OR
Please Use
arrayOfLines = lineString.match(/[^\r\n]+/g);
For an array of non empty Lines