Wednesday, July 3, 2024
HomeLanguagesJavascriptHow to add line breaks to an HTML textarea?

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:




<!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 neveropen. Geeks for neveropen. Geeks for neveropen. Geeks for neveropen.

Code with line break:

Geeks for neveropen. 
Geeks for neveropen. 
Geeks for neveropen. 
Geeks for neveropen.

Calisto Chipfumbu
Calisto Chipfumbuhttp://cchipfumbu@gmail.com
I have 5 years' worth of experience in the IT industry, primarily focused on Linux and Database administration. In those years, apart from learning significant technical knowledge, I also became comfortable working in a professional team and adapting to my environment, as I switched through 3 roles in that time.
RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments