JavaScript: Split a multiline string into an array of lines

JavaScript fundamental (ES6 Syntax): Exercise-139 with Solution

Write a JavaScript program to split a multiline string into an array of lines.

  • Use String.prototype.split() and a regular expression to match line breaks and create an array.

Sample Solution:

JavaScript Code:

//#Source https://bit.ly/2neWfJ2 
const splitLines = str => str.split(/\r?\n/);
console.log('Original string:');
console.log('This\nis a\nmultiline\nstring.\n');
console.log(splitLines('This\nis a\nmultiline\nstring.\n'));

Sample Output:

Original string:
is a

["This","is a","multiline","string.",""]

Pictorial Presentation:

JavaScript Fundamental: Split a multiline string into an array of lines.


flowchart: Split a multiline string into an array of lines

Live Demo:

See the Pen javascript-basic-exercise-139-1 by w3resource (@w3resource) on CodePen.

Improve this sample solution and post your code through Disqus

Previous: Write a JavaScript program that takes a variadic function and returns a closure that accepts an array of arguments to map to the inputs of the function.
Next: Write a JavaScript program to get the highest index at which value should be inserted into array in order to maintain its sort order, based on a provided iterator function.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.

JavaScript: Tips of the Day

Chunks an array into n smaller arrays


const tips_chunkIntoN = (arr, n) => {
  const size = Math.ceil(arr.length / n);
  return Array.from({ length: n }, (v, i) =>
    arr.slice(i * size, i * size + size)
console.log(tips_chunkIntoN([1, 2, 3, 4, 5, 6, 7,8], 4));