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>
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>
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).