EN
Node.js - split string by new line character (JavaScript)
4
points
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:
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']