Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Process whitespaces from user input

The only reason why I include Python in the question is that PHP has the nl2br function that inserts br tags, a similar function in Python could be useful, but I suspect that this problem can be solved with HTML and CSS.

So, I have a form that receives user`s input in a textarea. I save it to the database, which is Postgres and then when I display it, it doesn't include the line breaks the user supplied to separate paragraphs.

enter image description here

I tried using the white-space CSS property on the paragraph tag:

white-space: pre

or

white-space: pre-wrap

But, this is weird, the result was separated lines but the first line aligned in the middle:

enter image description here

including text-align:left didn't solve the problem. I'm sure there is a simple solution to this.

like image 287
Alejandro Veintimilla Avatar asked Dec 06 '25 03:12

Alejandro Veintimilla


1 Answers

I would suggest to replace newline characters with <br /> either before storing it in the database (only once) or when fetching it (see comment).

With Python:

import re
myUserInput = re.sub('(?:\r\n|\r|\n)', '<br />', myUserInput)

With JavaScript (see jsfiddle):

myUserInput = myUserInput.replace(/(?:\r\n|\r|\n)/g, '<br />');
like image 189
dwitvliet Avatar answered Dec 07 '25 17:12

dwitvliet



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!