Alejandro Veintimilla
Alejandro Veintimilla

Reputation: 11543

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.

Upvotes: 3

Views: 150

Answers (1)

dwitvliet
dwitvliet

Reputation: 7671

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 />');

Upvotes: 4

Related Questions