Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Split string in javascript by lines, preserving newlines?

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).

like image 483
tuomassalo Avatar asked Sep 06 '25 09:09

tuomassalo


1 Answers

You can perform a global match with this pattern: /[^\n]+(?:\r?\n|$)/g

It matches any non-newline character then matches an optional \r followed by \n, or the end of the string.

var input = "foo\r\n\nbar\nbaz";
var result = input.match(/[^\n]+(?:\r?\n|$)/g);

Result: ["foo\r\n", "bar\n", "baz"]

like image 52
Ahmad Mageed Avatar answered Sep 09 '25 04:09

Ahmad Mageed