Files and data

Normalize text line endings deliberately

Replace CRLF and standalone CR with LF when a text-processing workflow needs one line-ending convention. Apply this only to text whose content permits that transformation.

Worked example

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

const original = "first\r\nsecond\rthird\n";
const normalized = original.replace(/\r\n|\r/g, "\n");
console.log(JSON.stringify(normalized));

How it works

Matching CRLF first prevents it from becoming two separate breaks. Existing LF characters remain unchanged. Normalizing once at an import boundary can simplify later parsing when the format defines line breaks independently of the original byte representation.

Limits and mistakes

The transformation changes bytes and invalidates hashes or signatures of the original file. Do not apply it to binary data, and be careful with formats where exact embedded text matters. Keep an untouched original when provenance is important.

Check the result

Expect "first second third ". Check CRLF, CR, LF, mixed input, and content without any line breaks. Verify a second normalization pass leaves the result unchanged.

Sources

Reference documentation for the behavior used in this guide: