What is the newline character in JavaScript strings across platforms? | A1Lab@FahadM to JavaScriptEnglish • 3 days ago

What is the newline character in JavaScript strings across platforms?

message-square
0

In JavaScript strings across platforms, the standard newline character is "\n" (Line Feed, U+000A), whereas Windows text files and terminals often use "\r\n" (Carriage Return U+000D + Line Feed U+000A) and classic/older systems sometimes produced lone "\r" (Carriage Return). Inside a JavaScript string literal, "\n" is always a single LF character regardless of whether your code runs on Linux, macOS, or Windows, so when reading external text or normalizing line endings across platforms, split or replace with /\r\n|\r|\n/.


1. The Standard Newline Escape Sequence in JavaScript ("\n")

In JavaScript string literals and template literals, "\n" represents a single Line Feed character (0x0A), while "\r" represents Carriage Return (0x0D):

// Inspect newline characters and their character codes in JavaScript strings
const lfOnly = "Line 1\nLine 2";
const crlfWindows = "Line 1\r\nLine 2";

console.log(lfOnly.split("\n"));      // ["Line 1", "Line 2"]
console.log(crlfWindows.split("\n")); // ["Line 1\r", "Line 2"] (note trailing "\r")
console.log("\n".charCodeAt(0));      // 10 (0x0A)
console.log("\r".charCodeAt(0));      // 13 (0x0D)
  • Single character in memory: A JavaScript string containing "\n" has length 1 for that newline, even on Windows.
  • Template literals preserve literal newlines: Multi-line template literals normalize source line breaks to "\n" inside the resulting string.

2. Normalizing and Splitting Mixed Line Endings (\r\n, \r, \n)

External inputs—such as user-pasted text, form <textarea> values, HTTP payloads, or cross-platform files—can mix \r\n and \n, so normalize line endings before splitting or counting lines:

// Normalize \r\n and \r line endings to "\n", or split into clean lines
function normalizeLineEndings(text, newline = "\n") {
  if (typeof text !== "string") {
    throw new TypeError("Expected text to be a string.");
  }

  return text.replace(/\r\n|\r|\n/g, newline);
}

function splitLinesCrossPlatform(text) {
  return normalizeLineEndings(text, "\n").split("\n");
}

// Example usage:
const mixedInput = "First\r\nSecond\nThird\rFourth";
console.log(splitLinesCrossPlatform(mixedInput));
// ["First", "Second", "Third", "Fourth"]
  • Replace \r\n first in alternation: Putting \r\n before \r in /\r\n|\r|\n/g ensures Windows pairs become a single newline instead of leaving stray \n characters.
  • Be careful with .split(/\r?\n/): That pattern handles \n and \r\n, whereas /\r\n|\r|\n/ also handles standalone \r.

3. Platform OS Line Endings in Node.js (os.EOL)

When writing files or console output in Node.js that should match the host operating system’s native line-ending convention, use EOL from node:os rather than hardcoding "\n" or "\r\n" for file output:

// Use the host OS line ending in Node.js when writing platform-native text files
import { EOL } from "node:os";

function joinWithOsEol(lines) {
  if (!Array.isArray(lines)) {
    throw new TypeError("Expected lines to be an array.");
  }

  return lines.join(EOL);
}

// Example usage:
console.log(JSON.stringify(EOL)); // "\n" on POSIX (Linux/macOS), "\r\n" on Windows
console.log(joinWithOsEol(["alpha", "beta"]));
  • os.EOL vs. JS string newline: os.EOL reflects the OS convention ("\n" on Linux/macOS, "\r\n" on Windows), while "\n" remains the standard newline character inside JavaScript strings, JSON, and network protocols.
  • JSON requires \n escapes: In valid JSON text, raw unescaped control characters inside strings are invalid—JSON uses the two-character escape sequence \n to represent a newline.

TL;DR: The newline character in JavaScript strings across all platforms is "\n" (LF, code 10), while Windows files often use "\r\n" (CRLF); use /\r\n|\r|\n/ when normalizing or splitting cross-platform text, and os.EOL in Node.js when writing OS-native lines.