How To Split A String By Newline In JavaScript?

Working with strings is a common task in JavaScript, and sometimes you need to split a string into smaller parts based on a specific delimiter. In this tutorial, you will learn how to split a string by newline in JavaScript using different methods.

Table of Contents #
  1. Using the split() Method
  2. Trimming Whitespace
  3. Splitting Lines from TextArea Input

1. Using the split() Method

The split() method is a built-in JavaScript method for splitting a string into an array of substrings based on a specified delimiter. To split a string by newline, you can pass '\n' as the delimiter to the split() method.

const multilineString = "Line 1\nLine 2\nLine 3";

const lines = multilineString.split('\n');

console.log(lines);

Output:

[ 'Line 1', 'Line 2', 'Line 3' ]

In this example, the multilineString is split into an array of lines using '\n' as the delimiter. The resulting lines array contains three elements, each representing a line from the original string.

2. Trimming Whitespace

Sometimes, you may want to remove leading and trailing whitespace from each line after splitting the string. You can achieve this by using the trim() method in combination with map(). Here’s an example:

const multilineString = "  Line 1  \n Line 2 \n  Line 3  ";

const lines = multilineString.split('\n').map(line => line.trim());

console.log(lines);

Output:

[ 'Line 1', 'Line 2', 'Line 3' ]

In this example, we first split the multilineString by '\n', creating an array of lines. Then, we use the map() method to iterate over each line and apply the trim() method to remove any leading or trailing whitespace.

3. Splitting Lines from TextArea Input

If you want to split lines from the content of a textarea element in a web page, you can access the textarea’s value property and then split the string as shown earlier.

Here’s an example using HTML and JavaScript:

<!DOCTYPE html>
<html>
    <head>
        <title>Split String by Newline</title>
    </head>
    <body>
        <textarea id="inputText"></textarea>
        <button onclick="splitText()">Split</button>
        <pre id="output"></pre>

        <script>
            function splitText() {
                const inputText = document.getElementById('inputText').value;
                const lines = inputText.split('\n').map((line) => line.trim());
                document.getElementById('output').textContent = JSON.stringify(lines, null, 2);
            }
        </script>
    </body>
</html>

In this example, we have an HTML textarea element with an associated button. The splitText() function reads the text from the textarea, splits it by newline, trims whitespace, and displays the result in a <pre> element.