W3jar
152 words
1 minutes

How to Split a String by New Line in JavaScript

In JavaScript, you can split a string by newline characters using the split method. Newline characters can vary depending on the operating system:

  • Unix/Linux/Mac: \n
  • Windows: \r\n

Here’s a simple example to split a string by newlines:

// Example string with Unix-style newlines
const str = `Line 1
Line 2
Line 3`;

// Split the string by newline characters
const lines = str.split("\n");

console.log(lines); // Output: ['Line 1', 'Line 2', 'Line 3']

For cross-platform compatibility (handling both \n and \r\n), you can use a regular expression with the split method:

// Example string with mixed newline styles
const str = `Line 1\r\nLine 2\nLine 3\rLine 4`;

// Split the string by any type of newline characters
const lines = str.split(/\r?\n|\r/);

console.log(lines); // Output: ['Line 1', 'Line 2', 'Line 3', 'Line 4']

In the regular expression /\r?\n|\r/:

  • \r?\n matches both Unix-style and Windows-style newlines.
  • \r handles old Mac-style newlines.

This approach ensures that you correctly split the string regardless of the newline format used.