Encodera

Thanks for reading!

Donate to the site — we work hard for you.

How to split text into lines

Short answer

Split the text by the line break character \n:

const text = 'first\nsecond\nthird';
 
console.log(text.split('\n'));

Output:

[
  "first",
  "second",
  "third"
]

Windows line endings

Text from Windows files ends lines with \r\n. The pattern \r?\n handles both kinds:

const text = 'first\r\nsecond\nthird';
const lines = text.split(/\r?\n/);
 
console.log(lines.length, JSON.stringify(lines[0]));

Output:

3 "first"

Without empty lines

Trim each line and remove the empty ones:

const text = `
  apples
 
  pears
`;
const lines = text.split('\n').map((line) => line.trim()).filter(Boolean);
 
console.log(lines.join(', '));

Output:

apples, pears

Common mistake

If the text ends with a line break, the last element is an empty string:

console.log('a\nb\n'.split('\n').length);

Output:

3

Functions used in this recipe

Thanks for reading!

Donate to the site — we work hard for you.