How to Split a String by Newline in JavaScript

avatar

Borislav Hadzhiev

Wed Nov 17 20212 min read

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, 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. It's by far the best one out there.

There might be an edge case you need to handle - what if the string ends with a newline character. In this case, the split method would contain an empty string as the last element.
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 its boolean representation 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.

Join my newsletter

I'll send you 1 email a week with links to all of the articles I've written that week

Buy Me A Coffee