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:
Flowchart:

Live Demo:
See the Pen javascript-basic-exercise-139-1 by w3resource (@w3resource) on CodePen.
For more Practice: Solve these Related Problems:
- Write a JavaScript program that splits a multiline string into an array of individual lines.
- Write a JavaScript function that processes a string with newline characters and returns an array where each element is a line.
- Write a JavaScript program that trims and splits a block of text by line breaks into an array of strings.
Go to:
PREV : Variadic Function with Array Inputs.
NEXT : Highest Index for Sorted Insertion (With Iterator).
Improve this sample solution and post your code through Disqus
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.