How to add line breaks to an HTML textarea?

Way of implementing line breaks differ from one platform to another. The following approach takes input text from HTML Textarea and adds line breaks using JavaScript.

Approach:
This task can be achieved by using some predefined array and string functions provided by JavaScript. In the following code, the input from the textarea is processed by JavaScript on the click of the submit button to produce a required output with line breaks.

Functions Used:
split(): is a predefined JavaScript function that splits a string into an array using a parameter.
join(): is a predefined JavaScript function that joins an array to convert it into a string using provided parameters.

Example:

filter_none

edit
close

play_arrow

link
brightness_4
code

<!DOCTYPE html>
<html>
  
<head>
  
    <script type="text/javascript">
        function divide() {
            var txt;
            txt = document.getElementById('a').value;
            var text = txt.split(".");
            var str = text.join('.</br>');
            document.write(str);
        }
    </script>
    <title></title>
</head>
  
<body>
    <form>
        ENTER TEXT:
        <br>
        <textarea rows="20" 
                  cols="50" 
                  name="txt" 
                  id="a">
      </textarea>
        <br>
        <br>
        <input type="submit" 
               name="submit"
               value="submit" 
               onclick="divide()" />
    </form>
</body>
  
</html>

chevron_right


Output:
Code without line break:

Geeks for geeks. Geeks for geeks. Geeks for geeks. Geeks for geeks.

Code with line break:

Geeks for geeks. 
Geeks for geeks. 
Geeks for geeks. 
Geeks for geeks.

full-stack-img




My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.


Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.