How to add line breaks to an HTML textarea?


To add line breaks to an HTML textarea, we can use the HTML line break tag to insert a line break wherever we want. Alternatively, we can also use the CSS property "white-space: pre-wrap" to automatically add line breaks to the text. This is particularly useful when displaying pre-formatted text in a textarea. Therefore, let’s discuss the approach for adding the line breaks.

Approach

  • Create a textarea in HTML and assign an id to it.

  • Create a button which when clicked will split the textarea’s text using newline.

  • Now create the function which will break the text into newline. The code for this function will be −

function replacePeriodsWithLineBreaks() {
   // Get the textarea element
   var textarea = document.getElementById("textarea");
   
   // Get the text from the textarea
   var text = textarea.value;
   
   // Replace periods with line breaks
   text = text.replace(/\./g, "
"); // Update the textarea with the new text textarea.value = text; }

Example

The final code for this approach will be −

<!DOCTYPE html>
<html>
<head>
   <title>Add Line Breaks</title>
</head>
   <body>
      <textarea id="textarea" rows="10" cols="50"></textarea>
      <br>
      <button id="replace-btn" onclick="replacePeriodsWithLineBreaks()">Replace Periods with Line Breaks</button>
      <script>
         // Function to replace periods with line breaks in the textarea
         function replacePeriodsWithLineBreaks() {
            // Get the textarea element
            var textarea = document.getElementById("textarea");
            
            // Get the text from the textarea
            var text = textarea.value;
            
            // Replace periods with line breaks
            text = text.replace(/\./g, "
"); // Update the textarea with the new text textarea.value = text; } </script> </body> </html>

In this example, the JavaScript code first gets the textarea element by its id using the getElementById() method. Then, it gets the text from the textarea using the value property. Next, it uses the replace() method to replace all instances of periods with line breaks. Finally, it updates the textarea with the new text using the value property.

Note: The g flag in the regular expression /\./g is used to replace all occurrences of the period. Without it, only the first occurrence would be replaced.

Updated on: 09-Feb-2023

10K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements