The Wayback Machine - https://web.archive.org/web/20240910003000/https://www.geeksforgeeks.org/how-to-split-multiline-string-into-an-array-of-lines-in-javascript/
Open In App

How to split multiline string into an array of lines in JavaScript ?

Last Updated : 05 Jan, 2023
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Multiline string in JavaScript means a string having two or more lines. To split a multiline string into an array we need to use split() in our JavaScript code. 

JavaScript split(separator, limit) Method: The split() function is used to split the data depending upon the attributes we are passing in it. The separator attributes specify that from this word/sign the string will be divided. The limit attribute is optional, it specifies how many splits will be there.

Example 1: This example shows the use of the above approach. In this, when we will click on the “Go” button the array of the multiline string will be displayed on the screen separated by “,”.

HTML




<h1 style="color:green">
    Welcome to Geeks for Geeks
</h1>
<h3>
    Split multiline string into an array of lines in JavaScript
</h3>
<button onclick="myFunction()">
    Go
</button>
 
<p id="StringToArray"></p>
 
<script>
    function myFunction() {
        var string = "Are you ready?"
            + "<br>So let's get started";
     
        var array = string.split("<br>");
     
        document.getElementById("StringToArray")
            .innerHTML = array;
    }
</script>


Output:

 Split multiline string into an array of lines

 Split multiline string into an array of lines 

Example 2: Now, let’s see how to get a particular index of an array.

HTML




<h1 style="color:green">
    Welcome to Geeks for Geeks
</h1>
<h3>
    Split multiline string into an array of lines in JavaScript
</h3>
 
<button onclick="myFunction()">Go</button>
 
<p id="StringToArray"></p>
 
<script>
    function myFunction() {
        var string = "Are you ready?"
            + "<br>So let's get started";
     
        var array = string.split("<br>");
     
        document.getElementById("StringToArray")
            .innerHTML = array[1];
    }
</script>


Output:

 Split multiline string into an array of lines

 Split multiline string into an array of lines 

As we wrote array[1], hence only the 2nd line has been printed. If we will write array[2], then it will be undefined as this array contains data in the first two indexes only that are 0 and 1 respectively.

Example 3: Now, let’s try to take a string as user input.

HTML




<h1 style="color:green">
    Welcome to Geeks for Geeks
</h1>
<h3>
    split multiline string into an
    array of lines in JavaScript
</h3>
 
<textarea id="write" placeholder="Write something"
          style="height:100px;">
</textarea>
 
<button onclick="myFunction()">Go</button>
 
<p id="StringToArray"></p>
 
 
<script>
    function myFunction() {
     
        var string = document
            .getElementById("write").value;
     
        var array = string.split(".");
     
        document.getElementById("StringToArray")
            .innerHTML = array;
    }
</script>


Output:

 Split multiline string into an array of lines

 Split multiline string into an array of lines 



Similar Reads

JavaScript RegExp multiline Property
The multiline Property property in Javascript is used to specify whether the "m" modifier is set or not. If the "m" modifier is set than this property returns true else false. Syntax: RegexObj.multiline Return Value: It returns true if m modifier is set, else false. Example 1: This example checks if the regular expression contains m Modifier or not
1 min read
Displaying inline and multiline blocks of code using Bootstrap
Bootstrap provides a number of classes for displaying inline and multiline blocks of code. Displaying Inline Code: Inline code should be wrapped in &lt;code&gt; tags. The resulting text will be displayed in a fixed-width font and given a red font color. Note: The &lt; and &gt; tags should be replaced with &amp;lt; and &amp;gt; respectively. Below i
3 min read
How to create a multiline input control text area in HTML5 ?
The HTML &lt;textarea&gt; tag is used to specify a multiline input control text area in HTML5. The &lt;cols&gt; and &lt;rows&gt; attributes specify size of a textarea. Syntax &lt;textarea rows="" cols=""&gt; Contents... &lt;/textarea&gt; The &lt;textarea&gt; tag contains 5 attributes that are listed below: cols: It specifies width of textarea.rows:
1 min read
Spectre Multiline Tooltips
Spectre Tooltips are quite useful for showing the description of different elements in the webpage. Tooltip can be invoked on any element in a webpage. It provide context information labels that appear on hover and focus. Tooltips component is built entirely in CSS. The normal tooltip will try to display the data-tooltip content in a single line, s
2 min read
Bulma Multiline Option
Bulma is a free and open-source CSS framework used to build responsive and beautiful websites. It is based on flexbox. In this article, we will be seeing the multiline option in columns in Bulma. So, by default, all the columns inside a column container will be in the same row but we can use the is-multiline modifier on the columns container to mak
2 min read
Vue.js Form Input Binding with Multiline text
Vue.js is a progressive javascript framework for developing web user interfaces. It is a versatile framework providing high speed and performance. We can create Single Page Applications as well as Full Stack applications. Input Binding is used to sync and maintain the state of form input elements with the corresponding state in javascript. So, Vue.
2 min read
Blaze UI Typography Inline and Multiline code
Blaze UI is a CSS open-source framework. It is a lightweight UI toolkit and provides great tools for building customized and scalable applications. It can work with any framework that exists. It can adapt to any ecosystem. All designs or CSS are mobile-first and hence responsive. It project is available open-source so a large community maintains it
2 min read
React.js Blueprint Editable text Component Multiline mode
BlueprintJS is a React-based UI toolkit for the web. This library is very optimized and popular for building interfaces that are complex data-dense for desktop applications. Editable Text Component provides a way for users to provide content that is editable when the user clicks on it. Editable text Component Multiline Mode Properties: multiline: A
3 min read
How to Apply an Ellipsis to Multiline Text in CSS ?
Ellipsis refers to three dots (...) and is a user-friendly UI modification that indicates more information is available but has been truncated due to lack of space. In this article, we will explore two approaches to applying ellipses to multi-line text in CSS. Understanding Ellipsis in CSSEllipsis helps in providing a visual cue to users that there
3 min read
How to Switch Textarea to Multiline When Overflown with Text in CSS ?
In this article, we will see how the textarea can be switched to multiline while the text is overflowing, along with understanding the different ways to accomplish this task along with its implementation. Many times we have seen when users are typing in a textarea, they might not always know how much text will fit into the box. As a result, the tex
3 min read
Split a String into an Array of Words in JavaScript
JavaScript allows us to split the string into an array of words using string manipulation techniques, such as using regular expressions or the split method. This results in an array where each element represents a word from the original string. This can be achieved by using the following methods. Table of Content Using the split() methodUsing match
6 min read
JavaScript Program to Split a String into a Number of Sub-Strings
Given a string, the task is to split the string into number of sub-strings using JavaScript. This task is common in scenarios where data needs to be segmented or processed in chunks. This article provides a flexible solution that can divide a given string into a desired number of smaller substrings, allowing for efficient manipulation or analysis o
2 min read
JavaScript Program to Check if Given String can be Split into Four Distinct Strings
A string can be split into four distinct strings by identifying specific delimiters or patterns within the original string and extracting substrings based on these divisions, resulting in four separate and non-overlapping text segments. In this article, we will check if a given string can be split into four distinct strings. Table of Content Using
6 min read
How To Split a String Into Segments Of n Characters in JavaScript?
When working with JavaScript, you might encounter a situation where you need to break a string into smaller segments of equal lengths. This could be useful when formatting a serial number, creating chunks of data for processing, or splitting a long string into manageable pieces. In this article, we will explore various ways to split a string into s
6 min read
How to Split a String into an Array in PHP ?
In PHP, splitting a string into an array involves breaking a string into smaller parts based on a delimiter or a pattern and storing those parts as elements of an array. This operation is useful for parsing text data, extracting substrings, or processing user input. PHP provides several functions to split a string into an array, including explode(
2 min read
Split an array into chunks in JavaScript
Splitting an array into chunks in JavaScript involves dividing the array into smaller arrays of a specified size. This process is useful for managing large datasets more efficiently or for processing data in smaller, more manageable portions within the application. Methods to split the array into chunks: Table of Content Using JavaScript slice() Me
4 min read
How to break JavaScript Code into several lines ?
In this article, we will discuss how to break javascript code into several lines. We generally break the code into several lines so that it can be read easily by a third person or the programmer itself. There are a few ways to break JavaScript code into several lines: We can use the backslash \ character i.e "\". We can use template literals.We can
1 min read
Split a Sentence into Fixed-Length Blocks without Breaking Words in JavaScript
Given a sentence, our task is to split it into blocks of a fixed length without breaking words using JavaScript. Example: Input: Sentence= "This is a sample sentence to demonstrate splitting into blocks without breaking words.", blocksize = 15Output:Blocks: [ 'This is a', 'sample sentence ', 'to demonstrate', 'splitting into', 'blocks without', 'br
3 min read
Split a number into individual digits using JavaScript
We will get some input from the user by using &lt;input&gt; element and the task is to split the given number into the individual digits with the help of JavaScript. There are several approaches to splitting a number into individual digits using JavaScript which are as follows: Table of Content Using number.toString() and split('')Direct Character
3 min read
JavaScript Program to Split Map Keys and Values into Separate Arrays
In this article, we are going to learn about splitting map keys and values into separate arrays by using JavaScript. Splitting map keys and values into separate arrays refers to the process of taking a collection of key-value pairs stored in a map data structure and separating the keys and values into two distinct arrays. The map is a data structur
5 min read
How to split each element of an array of strings into different categories using Node.js?
The task is to split each element of a string array into different categories. Example: Input Array : const input = ['abc', 'def', 'ghi', 'jkl', 'mno', 'pqr', 'stw', 'xyz'] Category Array : const categories = ['a', 'b', 'c'] Split Size : const split_size = 3 Output:[ a: [ 'abc', 'def', 'ghi' ], b: [ 'jkl', 'mno', 'pqr' ], c: [ 'stw', 'xyz' ] ] Appr
2 min read
How to Split an Array of Strings into Chunks of Equal Length in TypeScript ?
In TypeScript, to split an array of strings into chunks of equal length we need to divide the array into the smaller subarrays, in which each contains the number of elements based on the chunk size. These are the following approaches:Table of Content Using for LoopUsing Array.from() methodUsing reduce() methodUsing for LoopIn this approach, we use
3 min read
JavaScript | Split a string with multiple separators
Given a statement which contains the string and separators, the task is to split the string into substring.String split() Method: The str.split() function is used to split the given string into array of strings by separating it into substrings using a specified separator provided in the argument. Syntax: str.split(separator, limit) Parameters: This
3 min read
JavaScript String.Split() Example with RegEx
The String.split() method in JavaScript is used to split a string into an array of substrings based on a specified delimiter. When a regular expression (RegEx) is used as the delimiter, it allows for more complex and powerful splitting criteria. This is particularly useful for splitting strings based on patterns rather than static characters. By le
2 min read
JavaScript String split() Method
JavaScript split() method proves invaluable for breaking down strings into arrays of substrings, utilizing a designated separator as a reference point. This method breaks the original string into segments wherever the separator occurs, generating an array where each element corresponds to a distinct substring. By using split(), developers gain a po
4 min read
Javascript Program to Split the array and add the first part to the end | Set 2
Given an array and split it from a specified position, and move the first part of array add to the end.   Examples:   Input : arr[] = {12, 10, 5, 6, 52, 36} k = 2 Output : arr[] = {5, 6, 52, 36, 12, 10} Explanation : Split from index 2 and first part {12, 10} add to the end . Input : arr[] = {3, 1, 2} k = 1 Output : arr[] = {1, 2, 3} Explanation :
2 min read
How to Split JavaScript Array in Chunks using Lodash?
Splitting a JavaScript array into chunks consists of dividing the array into smaller subarrays based on a specified size or condition. In this article, we will explore different approaches to splitting JavaScript array into chunks using Lodash. Below are the approaches to Split JavaScript array in chunks using Lodash: Table of Content Using Lodash
2 min read
Split JavaScript Array in Chunks Using Lodash?
When working with arrays in JavaScript, you may encounter situations where you need to split an array into smaller chunks. This can be particularly useful when dealing with large datasets or when performing operations in a more manageable and efficient manner. The Lodash library provides a convenient method to achieve this. This article will guide
2 min read
Remove new lines from string in PHP
Given a multiple line sentence or statement the task is to convert the whole statement in a single line. See the example below. Examples: Input : Hello welcome to geeksforgeeks.Output : Hello welcome to geeksforgeeks.Remove the new line between Hello and geeksforgeeks.Input : I love geeksforgeeksOutput : I love geeksforgeeksHere are some common app
2 min read
How to Set the Distance between Lines in a Text with JavaScript ?
In this article, we will see how to create a user-defined space between two consecutive lines to beautify the view using JavaScript. To set the distance between lines, we can use the line height Property. The line-height property is used to set or return the distance between lines in a text. Syntax: The Syntax for the line-Height property is as fol
3 min read