How to get textarea values with line breaks using JavaScript

← PrevNext →

We often use a <textarea> element in a form, to allow users to enter multi line text. Multi line texts will have line breaks, that is, you type a sentence and then hit the Enter key to go to the next line. I’ll show you how to extract or get the textarea values or those multi line texts with the line breaks using JavaScript.

See this example first. I have a <textarea> and a <div> element on my web page. I wish to extract values from the <textarea> and write it into the <div> element.

<div id='theText'>
    will write text here...
</div>
<p>
    <textarea onkeyup='writeText(this)' id='taYourText'></textarea>
</p>

<script>
  let t;

  let writeText = (ele) => {
    t = ele.value;
    document.getElementById('theText').innerHTML = t;
  }
</script>
Try it

In the above example, the script will extract and write the values from the textarea to the <div> in a straight line, even if the textarea has multi-line texts. Click the Try it button and see it for yourself.

Get textarea values with line breaks

Now try this script.

<body>
    <div id='theText'>
        will write text here...
    </div>
    <p>
        <textarea onkeyup='writeText(this)' id='taYourText'></textarea>
    </p>
</body>

<script>
  let t = '';

  let writeText = (ele) => {
    t = ele.value;
    document.getElementById('theText').innerHTML = t.replace(/\n\r?/g, '<br />');
  }
</script>
Try it

See the replace() function in the script. The t has the value from the textarea. The values may have line breaks.

Now understand RegEx or the regular expressions (as the first parameter) inside the replace() function. The \n denotes Line break or Line Feed. The \r denotes Carriage Return. The /g denotes global. So it says, do a global search for “\n” and “\r” and replace it with <br /> and write the text (or value) inside the element.

Also, if you have noticed, I am using innerHTML property to write values in the <div> with <br /> (line break).

← PreviousNext →