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, pearsCommon 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:
3Functions used in this recipe
- String.prototype.split — Splits a string into an array by a separator.
- String.prototype.trim — Removes whitespace from both ends of a string.
- Array.prototype.filter — Creates a new array from the elements that pass a test.