Skip to content
Related Articles

Related Articles

Improve Article
How to split multiline string into an array of lines in JavaScript ?
  • Last Updated : 13 Apr, 2021

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

split(separator, limit): 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:

HTML




<!DOCTYPE html>
<html>
  
<body>
  
    <h1>Welcome to Geeks for Geeks</h1>
  
    <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>
</body>
  
</html>

Output:



In this, when we will click on the “Go” button the array of the multiline string will be displayed on the screen separated by “,”.

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

HTML




<!DOCTYPE html>
<html>
  
<body>
  
    <h1>Welcome to Geeks for Geeks</h1>
  
    <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>
</body>
  
</html>

Output:

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 string as an user input.

HTML




<!DOCTYPE html>
<html>
  
<body>
    <h1>Welcome to Geeks for Geeks</h1>
  
    <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>
</body>
  
</html>

Output:




My Personal Notes arrow_drop_up
Recommended Articles
Page :