JavaScript

Split a small text string into lines

For a small in-memory text value, split on a line-ending expression that recognizes CRLF, LF, and CR. Keep or remove a trailing empty line according to the file format’s rules.

Worked example

Node.js example · save as example.mjs and run node example.mjs

const text = "first\r\nsecond\nthird\r";
const lines = text.split(/\r\n|\n|\r/);
console.log(JSON.stringify(lines));

How it works

The CRLF alternative comes first so a Windows line ending is treated as one separator. A trailing line ending produces a final empty string. That distinction can matter when a blank last record is meaningful rather than accidental.

Limits and mistakes

This allocates the complete line array and is not a streaming parser for large files. It also does not handle quoted multiline CSV records. Use a format-aware parser when line breaks may appear inside escaped fields.

Check the result

Expect ["first","second","third",""] for the sample. Test a file without a final newline and a file containing blank lines before choosing a cleanup policy.

Sources

Reference documentation for the behavior used in this guide: