w3resource

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:
This
is a
multiline
string.

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

Pictorial Presentation:

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

Flowchart:

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.



Follow us on Facebook and Twitter for latest update.