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:
xxxxxxxxxx
1
const os = require('os');
2
3
const text = 'line 1\r\nline 2';
4
const lines = text.split(os.EOL); // or: text.split(/\r?\n/)
5
6
console.log(lines); // ['line 1', 'line 2']
7
8
9
// os.EOL under:
10
//
11
// - Linux and macOS is \n
12
// - Windows is \r\n
Output:
xxxxxxxxxx
1
[ '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:
xxxxxxxxxx
1
var text = 'line 1\nline 2';
2
var lines = text.split(/\r?\n/); // splits text by \r\n or \n
3
4
console.log(lines); // ['line 1', 'line 2']
Hint: check this article to know more universal solutions.
There is available some npm
package to deal with newline characters.
Links:
Package installation:
xxxxxxxxxx
1
npm install eol --save
Usage example:
xxxxxxxxxx
1
const eol = require('eol'); // or: import eol from 'eol'
2
3
const text = 'line 1\r\nline 2';
4
const lines = eol.auto(text);
5
6
console.log(lines); // ['line 1', 'line 2']