Languages
[Edit]
EN

JavaScript - universal new lines splitting symbol example

5 points
Created by:
Zoya-Gaines
263

In this article, we're going to have a look at the problem of how to universal way to split strings to separate lines in JavaScript, when we work on mixed newline text.

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

Hint: check \R character 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);

Note:

The expression symbols order is very important to try to:

  • split text by two characters as newline symbol at first (\r\n or \n\r),
  • and later with single newline symbol (\n or \r).

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

for \n or \r at 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. 

See also

  1. JavaScript - split string by new line character
  2. JavaScript - \R equivalent in RegEx

Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

â€ïžđŸ’» 🙂

Join