Introduction
In this lab, we will explore how to split a multiline string into an array of lines using JavaScript. We will use the String.prototype.split() method and a regular expression to match line breaks and create an array of individual lines. This will be a useful skill for parsing and manipulating text data in web development projects.
How to Start Practicing Coding in Terminal/SSH
To start practicing coding in Terminal/SSH, simply type node.
Splitting a Multiline String into an Array of Lines
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. - The regular expression
/\r?\n/matches both\rand\nline breaks. - This will return an array of lines.
const splitLines = (str) => str.split(/\r?\n/);
splitLines("This\nis a\nmultiline\nstring.\n");
// ['This', 'is a', 'multiline', 'string.' , '']
Summary
Congratulations! You have completed the Split Into Lines lab. You can practice more labs in LabEx to improve your skills.