How to Split a String by Newline in JavaScript

avatar

Borislav Hadzhiev

Last updated: Jul 25, 2022

banner

Check out my new book

Split a String by Newline in JavaScript #

To split a string by newline, call the split() method passing it the following regular expression as parameter - /\r?\n/. The split method will split the string on each occurrence of a newline character and return an array containing the substrings.

index.js
const str = 'first\nsecond\r\nthird'; const result = str.split(/\r?\n/); // 👇️ ['first', 'second', 'third'] console.log(result);

We passed a regular expression to the String.split method.

The forward slashes / / mark the beginning and end of the regular expression.

We want to replace both \r and \n characters because the line breaks vary depending on the operating system.

For example, Windows uses \r\n as end of line character, whereas \n is the default in Unix.

The question mark ? matches the preceding item (\r) 0 or 1 times. In other words the \r might be there, or it might not be there.

If you ever need help reading a regular expression, bookmark this regex cheatsheet from MDN.

There might be an edge case you need to handle - what if the string ends with a newline character. In this case the last array element would be an empty string.
index.js
const str = 'first\nsecond\r\nthird\n'; const result = str.split(/\r?\n/); // 👇️ ['first', 'second', 'third', ''] console.log(result);

We split the string on newline characters, however there's nothing after the last newline, so we get an empty string as the last array element.

We can handle this by using the Array.filter method.

index.js
const str = 'first\nsecond\r\nthird\n'; const result = str.split(/\r?\n/).filter(element => element); // 👇️ ['first', 'second', 'third'] console.log(result);

The function we passed to the filter method gets called with each element in the array.

On each iteration, we return the element as is.

The filter method returns a new array that contains only the truthy values that the callback function returned.

Truthy are all the values that are not falsy.

The falsy values in JavaScript are: false, null, undefined, 0, "" (empty string), NaN (not a number).

The empty string is a falsy value, so it doesn't get added to the new array.

An alternative and more concise approach would be to pass the Boolean object to the filter method.

index.js
const str = 'first\nsecond\r\nthird\n'; const result = str.split(/\r?\n/).filter(element => element); // 👇️ ['first', 'second', 'third'] console.log(result);

The Boolean object takes each element from the array, converts it to a boolean and returns the result.

index.js
console.log(Boolean('test')); // 👉️ true console.log(Boolean('')); // 👉️ false

Empty strings are falsy values and get converted to false, therefore they don't get added to the new array.

Which approach you pick is a matter of personal preference. I'd go with explicitly returning the array element as I find the Boolean approach to be too implicit and indirect.

Use the search field on my Home Page to filter through my more than 3,000 articles.