Skip to content
Related Articles

Related Articles

Improve Article

How to add line breaks to an HTML textarea?

  • Last Updated : 28 Jan, 2020

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:




<!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>

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.



My Personal Notes arrow_drop_up
Recommended Articles
Page :