mdesantis
mdesantis

Reputation: 8517

Javascript regex: discard end of string match

I want to split a string preserving the newlines. The string can be everything, so the code must work in any case (new lines at begin of string, at end of string, consecutive new lines...).

I'm using this code:

var text = "abcd\nefg\n\nhijk\n"
var matches = text.match(/.*\n?/g)

which produces the following result:

[ 'abcd\n', 'efg\n', '\n', 'hijk', '' ]

That is what I need, except for the last match ('').

Actually I use matches.pop() in order to remove it, but I wonder if the regex could be improved in order to avoid that match.

Bonus points if you can explain why that match is present (I can't find any reason, but I suck at regexs :-) ).

Upvotes: 1

Views: 127

Answers (2)

Casimir et Hippolyte
Casimir et Hippolyte

Reputation: 89557

Use an alternative:

var text = "abcd\nefg\n\nhijk\n";
var matches = text.match(/.+\n?|\n/g);

Upvotes: 2

anubhava
anubhava

Reputation: 785098

You can use array#filter:

var matches = text.match(/.*\n?/g).filter(Boolean);
//=> [ 'abcd\n', 'efg\n', '\n', 'hijk' ]

Or using a slightly different regex with non-optional \n (but it assumes new line is always there after last line):

var matches = text.match(/.*\n/g);
//=> [ 'abcd\n', 'efg\n', '\n', 'hijk' ]

Upvotes: 1

Related Questions