How would I split a javascript string such as foo\nbar\nbaz to an array of lines, while preserving the newlines? I’d like to get ['foo\n', 'bar\n', 'baz'] as output;
I’m aware there are numerous possible answers – I’m just curious to find a stylish one.
With perl I’d use a zero-width lookbehind assertion: split /(?<=\n)/, but they are not supported in javascript regexs.
PS. Extra points for handling different line endings (at least \r\n) and handling the missing last newline (as in my example).
You can perform a global match with this pattern:
/[^\n]+(?:\r?\n|$)/gIt matches any non-newline character then matches an optional
\rfollowed by\n, or the end of the string.Result:
["foo\r\n", "bar\n", "baz"]