Languages
[Edit]
EN

Node.js - split string by new line character (JavaScript)

4 points
Created by:
Fletcher-Peralta
778

In this article, we're going to have a look at the problem of how to split string to separate lines in Node.js.

Example JavaScript source code run under Windows:

const os = require('os');

const text = 'line 1\r\nline 2';
const lines = text.split(os.EOL);  // or: text.split(/\r?\n/)

console.log(lines);  // ['line 1', 'line 2']


// os.EOL under:
//
//  - Linux and macOS is   \n
//  - Windows         is \r\n

Output:

[ 'line 1', 'line 2' ]

Note: depending on operating system we have different END OF LINE symbols.

 

In practice, applications exchange data with external environment - it forces programmer to take care of the different cases.

If we are looking for some simple universal solution we can use:

// ONLINE-RUNNER:browser;

var text = 'line 1\nline 2';
var lines = text.split(/\r?\n/); // splits text by \r\n or \n

console.log(lines);              // ['line 1', 'line 2']

Hint: check this article to know more universal solutions.

 

Other solutions

There is available some npm package to deal with newline characters.

Links:

  1. EOL - npm page
  2. EOL - GitHub page

Package installation: 

npm install eol --save

Usage example:

const eol = require('eol');  // or: import eol from 'eol'

const text = 'line 1\r\nline 2';
const lines = eol.auto(text);

console.log(lines);  // ['line 1', 'line 2']

 

See also

  1. JavaScript - split string by new line character

Alternative titles

  1. Node.js - split string by newline character (JavaScript)
  2. Node.js - split text by new line character (JavaScript)
  3. Node.js - split text by newline character (JavaScript)
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.
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