w3resource

JavaScript: Split a multiline string into an array of lines

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

Split Multiline String to Array

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

// Define the 'splitLines' function that splits a string into an array of lines.
const splitLines = str => str.split(/\r?\n/);

// Test the 'splitLines' function with a multiline string.
console.log('Original string:');
console.log('This\nis a\nmultiline\nstring.\n');
console.log(splitLines('This\nis a\nmultiline\nstring.\n'));

Output:

Original string:
This
is a
multiline
string.

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

Visual 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.



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://www.w3resource.com/javascript-exercises/fundamental/javascript-fundamental-exercise-139.php