Split Strings Into Line Array

JavaScriptJavaScriptBeginner
Practice Now

This tutorial is from open-source community. Access the source code

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.


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL javascript(("`JavaScript`")) -.-> javascript/BasicConceptsGroup(["`Basic Concepts`"]) javascript/BasicConceptsGroup -.-> javascript/variables("`Variables`") javascript/BasicConceptsGroup -.-> javascript/data_types("`Data Types`") javascript/BasicConceptsGroup -.-> javascript/arith_ops("`Arithmetic Operators`") javascript/BasicConceptsGroup -.-> javascript/comp_ops("`Comparison Operators`") subgraph Lab Skills javascript/variables -.-> lab-28622{{"`Split Strings Into Line Array`"}} javascript/data_types -.-> lab-28622{{"`Split Strings Into Line Array`"}} javascript/arith_ops -.-> lab-28622{{"`Split Strings Into Line Array`"}} javascript/comp_ops -.-> lab-28622{{"`Split Strings Into Line Array`"}} end

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 \r and \n line 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.

Other JavaScript Tutorials you may like