Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I make the whitespace behaviour in a <textarea> and a HTML preview match?

I have a <textarea> element. When the user fills it, you can see the spaces they made and when they pressed Enter to jump to the next line.

This is great, but when I see the HTML output, the result differs. It is an endless sentence without line breaks.

Using only HTML or JavaScript, how can I fix this?

like image 866
user1799565 Avatar asked Jan 30 '26 18:01

user1799565


2 Answers

You probably want something like:

<p style="white-space: pre-wrap"></p>
<p style="white-space: pre"></p>
<pre></pre>

pre-wrap:
Whitespace is preserved by the browser. Text will wrap when necessary, and on line breaks 
pre:
Whitespace is preserved by the browser. Text will only wrap on line breaks Acts like the <pre> tag in HTML
like image 175
light Avatar answered Feb 01 '26 07:02

light


If you are just taking what is entered in a textarea and outputing it as html, you would see this. For starters, you could replace all spaces with &nbsp; and all newlines with <br>. Or put the output in <pre> tags. (In either case, you will also want to replace some other characters with entities too.)

like image 31
ysth Avatar answered Feb 01 '26 08:02

ysth



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!