The below approach works with all operating systems:
// ONLINE-RUNNER:browser; var LINE_EXPRESSION = /\r\n|\n\r|\n|\r/g; // expression symbols order is very important var text = 'line 1\n' + 'line 2\r' + 'line 3\r\n' + 'line 4\n\r' + 'line 5'; var lines = text.split(LINE_EXPRESSION); console.log(lines);
\Rcharacter class-based example here.
More complicated example
HTTP GET method request response:
// ONLINE-RUNNER:browser; var LINE_EXPRESSION = /\r\n|\n\r|\n|\r/g; // expression symbols order is very important var text = '' + 'HTTP/1.1 200 OK\r\n' + 'Content-Length: 25\r\n' + 'Content-Type: text/html\r\n' + '\r\n' + 'Hello world!\n' + 'Some text...'; var lines = text.split(LINE_EXPRESSION); console.log(lines);
The expression symbols order is very important to try to:
- split text by two characters as newline symbol at first (
- and later with single newline symbol (
let's suppose we have HTTP protocol response:
HTTP/1.1 200 OK\r\nContent-Length: 25\r\nContent-Type: text/html\r\n\r\nHello world!\nSome text...
\rat begining of the expression we could get different number of newlines after splitting.
after splitting we should get:
HTTP/1.1 200 OK Content-Length: 25 Content-Type: text/html Hello world! Some text...
Second important thing is newline symbol unification per operationg system that makes posible to use below expression.